python Django rest-framework 创建序列化工程步骤

时间:2023-11-16 08:43:26
11创建项目
2创建应用
3stting添加应用(apps)-添加制定数据库-修改显示汉字(zh-hans)-上海时区(Asia/Shanghai)
4主路由添加子路由
5应用里创建子路由
6创建数据表结构-model
7创建serializer序列化
8编写views视图
-------------------- INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'demo_app1.apps.DemoApp1Config',
'rest_framework',
]
---------
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'my_1',
'USER':'root',
'PASSWORD':'',
'HOST':'127.0.0.1',
'PORT':,
}
}
LANGUAGE_CODE = 'zh-hans' TIME_ZONE = 'Asia/Shanghai' USE_I18N = True USE_L10N = True USE_TZ = True
---------
from django.contrib import admin
from django.urls import path
from django.conf.urls import url,include
urlpatterns = [
path('admin/', admin.site.urls),
url(r'^',include('demo_app1.urls')),
]
-------------------------------------- from django.db import models # Create your models here.
#创建user_name数据表
class user_name(models.Model):
nick_name = models.CharField(max_length=,verbose_name='昵称')
gender = models.BooleanField(default=,verbose_name='性别')
image = models.ImageField(upload_to='media',verbose_name='图片')
add_time = models.DateField(auto_now_add=True,verbose_name='时间')
phone = models.CharField(max_length=,verbose_name='手机')
class Meta:
#制定数据表
db_table = 'user'
#后端显示中文
verbose_name = '用户'
#制定显示中文
verbose_name_plural = verbose_name
def __str__(self):
#返回显示第一个字段
return self.nick_name
---------------------------
from rest_framework import serializers
#导入rest-framework序列化模块seralizer
from .models import user_name
#导入外部数据表
class UserSerializer(serializers.Serializer):
nick_name = serializers.CharField(max_length=,required=True)
gender = serializers.BooleanField(default=,required=False)
image = serializers.ImageField(required=False)
add_time = serializers.DateField(required=False)
phone = serializers.CharField(max_length=,required=False)
def create(self, validated_data):
#在乎句酷修改前端返回来的数据
return user_name.objects.create(**validated_data)
def update(self, instance, validated_data):
#只想数据表 获取前端返回数据 字段名 只想数据表字段名
instance.nick_name = validated_data.get('nick_name',instance.nick_name)
instance.gender = validated_data.get('gender',instance.gender)
instance.image = validated_data.get('image',instance.image)
instance.add_time = validated_data.get('add_time',instance.add_time)
instance.phone = validated_data.get('phone',instance.phone)
instance.save()
#数据表保存修改
return instance
#返回数据表
class UserModelSeralizer(serializers.ModelSerializer):
#创建类--序列化数据模型
class Meta:
#指向数据模型-数据表
model = user_name
#过滤数据表所有字段
fields = '__all__' -----------------------------------
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^users/$',views.UserGenericAPIView.as_view()),
url(r'users/(?P<pk>\d+)',views.UserGenericSingleView.as_view()), ]
-------------------------

views视图第一种写法最难
from .serializers import UserSerializer
from .models import User from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status # 用户API视图
class UserAPIView(APIView):
# 调用get方法
def get(self, request):
users = User.objects.all()
# 创建序列化器,many是集合(多个数据的时候)指定为True
ser = UserSerializer(instance=users, many=True)
# 返回响应 ser.data 是序列化之后的数据
return Response(ser.data, status=200) def post(self,request):
# instance:我们从数据库查出来的;data是前端获取的
ser = UserSerializer(data=request.data)
# is_valid校验是不是有效
if ser.is_valid():
ser.save()
return Response(ser.data, status=200)
return Response(ser.errors) class UserSingleView(APIView):
def get(self, request, pk):
user = User.objects.get(pk=pk)
ser = UserSerializer(user)
# status.HTTP_200_OK rest_framework的状态吗
return Response(ser.data, status=status.HTTP_200_OK) def put(self,request, pk):
user = User.objects.get(pk=pk)
# instance:我们从数据库查出来的;data是前端获取的
ser = UserSerializer(instance=user, data=request.data)
if ser.is_valid():
ser.save()
return Response(ser.data, status=200)
return Response(ser.errors) def delete(self, request, pk):
user = User.objects.get(pk=pk)
user.delete()
return Response(status=200)

 

views视图第二种写法难度还行
from django.shortcuts import render
from .serializer import UserModelSeralizer,UserSerializer
#导入序列化数据模型
from .models import user_name
#导入数据表
from rest_framework.views import APIView
#导入*APIVIEW接口视图模块
from rest_framework.response import Response
#导入返回模块
from rest_framework import status
#导入返回状态码模块
from rest_framework.generics import GenericAPIView
#导入下一级APIVIEW接口视图
from rest_framework import mixins
"""
------------------------------------
导入mixins模块
mixins.ListModelMixin-------定义list方法,返回一个queryser的列表---对应GET请求
mixins.CreateModelMixin-----定义create方法,创建一个实例----对应POST请求
mixins。RetrieveModelMixin--定义retrieve方法,返回一个具体的实例--对应GET请求
mixins。UpdateModelMixin----定义update方法,对某个实例进行更新----对应PUT--PATH请求
mixins。DestroyModelMixin---定义delete方法,删除某个实例,-----delete请求对应
------------------------------------
"""
# Create your views here.
class UserGenericAPIView(GenericAPIView,mixins.ListModelMixin,mixins.CreateModelMixin):
queryset = user_name.objects.all()
serializer_class = UserModelSeralizer
def get(self,request):
return self.list(request)
def post(self,request):
return self.create(request)
class UserGenericSingleView(GenericAPIView,mixins.RetrieveModelMixin,mixins.UpdateModelMixin,mixins.DestroyModelMixin):
queryset = user_name.objects.all()
serializer_class = UserModelSeralizer
def get(self,request,pk):
return self.retrieve(request)
def put(self,request,pk):
return self.update(request)
def delete(self,request,pk):
return self.destroy(request)
===================================
views视图第三种精简写法
from rest_framework.generics import ListAPIView,RetrieveAPIView,DestroyAPIView,CreateAPIView,UpdateAPIView
class cha(ListAPIView,CreateAPIView):
queryset = user_name.objects.all()
serializer_class = UserModelSeralizer
class gai(RetrieveAPIView,UpdateAPIView,DestroyAPIView):
queryset = user_name.objects.all()
serializer_class = UserModelSeralizer

最后记得去数据表里添加数据======