python Django实现增删改查实战代码
1.先创建个app子级
python .\manage.py startapp app01
然后创建数据模型
app01下的
modules.py文件
from django.db import models # Create your models here. class UserInfo(models.Model): name=models.CharField(max_length=32) password=models.CharField(max_length=12) age=models.IntegerField() tel=models.IntegerField(max_length=11)
配置数据库
"default": { "ENGINE": "django.db.backends.mysql", "NAME": "数据库名", "USER": "数据库用户名", "PASSWORD": "密码", "HOST": "127.0.0.1", "PORT": "3306", }
2.迁移数据库
python manage.py makemigrations 和 python manage.py migrate
3.写路由url
from django.contrib import admin from django.urls import path,include from app01 import views urlpatterns = [ # path("admin/", admin.site.urls), # path("index/",views.index), # path("user/list/", views.user_list), # path("login/", views.ApiLogin.as_view()), # path("del/", views.ApiDel.as_view()), path("add/", views.addUser.as_view()), path("user/", views.UserList.as_view()), path("updateuser/", views.upDateUser.as_view()), path("del/", views.deluser.as_view()), ]
4.view页面编写增删改查
from django.shortcuts import render,HttpResponse from rest_framework.views import APIView # Create your views here. from django import views from app01.models import UserInfo from rest_framework.response import Response from app01.ser import APIViewUserInfo class addUser(APIView): def post(self,request): obj=APIViewUserInfo(data=request.data) if obj.is_valid(): obj.save() return Response({"data":obj.data, "status" : 201,"message":"添加用户成功"}) return Response(data=obj.errors,status=400) class UserList(APIView): def get(self,request): obj=UserInfo.objects.all() ser=APIViewUserInfo(instance=obj,many=True) return Response(ser.data) class upDateUser(APIView): def post(self,request): print(request.data.get("id")) i=request.data.get("id") try: user=UserInfo.objects.get(id=i) except Exception as e: return Response(data="不存在", status=201) # 创建序列化对象,并将要反序列化的数据传递给data构造参数,进而进行验证 user.password=request.data.get("password") if request.data.get("name")!="": print(request.data.get("name")=="") user.name=request.data.get("name") user.save() return Response(status=400) class deluser(APIView): def post(self,request): id=request.data.get("id") UserInfo.objects.filter(id=id).delete() return Response({"msg":"删除成功","state":"true"}) # def index(request): # return HttpResponse("欢迎使用") # # # def user_list(request): # return render(request,"user_list.html") # # class ApiLogin(APIView): # def get(self,request): # return HttpResponse("get") # def post(self,request): # UserInfo.objects.create(name="张三",password="123456",age=15,tel="1234567891") # obj=UserInfo.objects.all() # print(obj) # return HttpResponse("post") # # class ApiDel(APIView): # def post(self,request): # UserInfo.objects.filter(id=4).delete() # return HttpResponse("删除成功")
5.序列化 反序列化
# -*- coding: utf-8 -*- from rest_framework import serializers from app01.models import UserInfo class APIViewUserInfo(serializers.Serializer): """图书数据序列化器""" id = serializers.IntegerField(label="ID", read_only=True) # 主键序列化 # 第一:普通字段序列化 name = serializers.CharField(label="名称", max_length=20) password = serializers.CharField(label="密码") age = serializers.IntegerField(label="年龄", required=False) tel = serializers.IntegerField(label="电话", required=False) # # 第二:一对多字段序列化 # heroinfo_set = serializers.PrimaryKeyRelatedField(read_only=True, many=True) # # 第三:自定义显示(显示多对多) # xxx = serializers.SerializerMethodField(read_only=True) class Meta: model = UserInfo # 自定义显示 多对多 字段 # 定义创建语法:ser.save()执行,就会立刻调用create方法用来创建数据 def create(self, validated_data): """validated_data: 表单或者vue请求携带的json:{"username":"zhangsan","password":"123456"}""" return self.Meta.model.objects.create(**validated_data)
到此这篇关于python Django增删改查 快速体验的文章就介绍到这了,更多相关python Django增删改查内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
X 关闭
X 关闭
- 15G资费不大降!三大运营商谁提供的5G网速最快?中国信通院给出答案
- 2联想拯救者Y70发布最新预告:售价2970元起 迄今最便宜的骁龙8+旗舰
- 3亚马逊开始大规模推广掌纹支付技术 顾客可使用“挥手付”结账
- 4现代和起亚上半年出口20万辆新能源汽车同比增长30.6%
- 5如何让居民5分钟使用到各种设施?沙特“线性城市”来了
- 6AMD实现连续8个季度的增长 季度营收首次突破60亿美元利润更是翻倍
- 7转转集团发布2022年二季度手机行情报告:二手市场“飘香”
- 8充电宝100Wh等于多少毫安?铁路旅客禁止、限制携带和托运物品目录
- 9好消息!京东与腾讯续签三年战略合作协议 加强技术创新与供应链服务
- 10名创优品拟通过香港IPO全球发售4100万股 全球发售所得款项有什么用处?