django rest_framework序列化,视图,分页整理

先建是数据库表models.py:

from django.db import models

class UserGroup(models.Model):
    title = models.CharField(max_length=32)

class UseInfo(models.Model):
    user_type_choices = (
        (1,'普通用户'),
        (2,'VIP'),
        (3,'SVIP'),
    )
    user_type = models.IntegerField(choices=user_type_choices)
    username = models.CharField(max_length=32,unique=True)#唯一索引
    password = models.CharField(max_length=64)

    group = models.ForeignKey('UserGroup',on_delete=models.CASCADE)
    roles = models.ManyToManyField('Role')

class UserToken(models.Model):
    user = models.OneToOneField(to='UseInfo',on_delete=models.CASCADE)
    token = models.CharField(max_length=64)

class Role(models.Model):
    title = models.CharField(max_length=32)

示例urls.py文件:

from rest_framework import routers
from django.urls import path,re_path,include
from api import views
router = routers.DefaultRouter()
router.register(r'rt',views.V4View)
urlpatterns = [
    path('parser/',  views.ParserView.as_view(),name='ddd'),
    path('roles/',  views.RolesView.as_view(),name='ddd'),
    path('userinfo/',  views.UserInfoView.as_view(),name='ddd'),
    re_path('group/(?P\d+)',  views.GroupView.as_view(),name='gp'),
    path('usergroup/',  views.UserGroupView.as_view(),name='ddd'),
    path('pager1/',  views.Pager1View.as_view()),
    path('pager2/',  views.Pager2View.as_view()),
    path('pager3/',  views.Pager3View.as_view()),
    path('v1/',  views.V1View.as_view()),
    path('v2/',  views.V2View.as_view({
     'get': 'list','post': 'xxx'})),
    # path('v3/',  views.V3View.as_view({'get': 'list','post': 'create'})),
    re_path('v3\.(?P\w+)',  views.V3View.as_view({
     'get': 'list','post': 'create'})),
    re_path('v4/(?P\d+)/',  views.V4View.as_view({
     'get': 'retrieve','delete': 'destroy','put': 'update','patch': 'partial_update'})),
                                                        #查看一条数据           删除               全部更新           局部更新

    # re_path(r'(?P[v1]+)/',include(router.urls))
    re_path('test\.(?P\w+)',  views.TestView.as_view()),
]

示例views.py文件(每一种方法写一个接口):

from django.shortcuts import render
from django.shortcuts import render,HttpResponse
from rest_framework.views import APIView
from rest_framework.request import Request
from api import models
import json
from rest_framework.parsers import JSONParser,FormParser
class ParserView(APIView):
    # parser_classes = [JSONParser,FormParser]

    def get(self,request,*args,**kwargs):
        """
        可以发JSON数据
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        print(request.data)

        return HttpResponse("ParserView")

from rest_framework import serializers # 序列化

class RolesSerializer(serializers.Serializer):
    id = serializers.IntegerField()
    title = serializers.CharField()

class RolesView(APIView):

    def get(self,request,*args,**kwargs):
        # 方法一
        # roles = models.Role.objects.all().values('id','title')
        # roles = list(roles)
        # ret = json.dumps(roles,ensure_ascii=False)#转编码

        # 方法二(多个对象)
        # roles = models.Role.objects.all()
        # ser = RolesSerializer(instance=roles,many=True)
        # # ser.data 返回的是字典
        # ret = json.dumps(ser.data,ensure_ascii=False)
        # 方法二(单个对象)
        roles = models.Role.objects.all().first()
        ser = RolesSerializer(instance=roles,many=False)
        # ser.data 返回的是字典
        ret = json.dumps(ser.data,ensure_ascii=False)
        return HttpResponse(ret)
# 方法一
# class UserInfoSerializer(serializers.Serializer):
#     # source源
#     types = serializers.CharField(source='get_user_type_display') # row.get_user_type_display
#     username = serializers.CharField()
#     password = serializers.CharField()
#     gp = serializers.CharField(source='group.title') # 外键
#     # rls = serializers.CharField(source='roles.all')
#     # 多对多
#     rls = serializers.SerializerMethodField()
#     def get_rls(self,row):
#         role_obj_list = row.roles.all()
#         ret = []
#         for item in role_obj_list:
#             ret.append({'id': item.id,'title': item.title})
#         return ret
# 方法二
# class UserInfoSerializer(serializers.ModelSerializer):
#     types = serializers.CharField(source='get_user_type_display')
#     rls = serializers.SerializerMethodField()# 自定义显示
#
#     class Meta:
#         model = models.UseInfo
#         fields = ['id','username','password','types','rls']
#
#     def get_rls(self,row):
#         role_obj_list = row.roles.all()
#         ret = []
#         for item in role_obj_list:
#             ret.append({'id': item.id,'title': item.title})
#         return ret

# 方法三
class UserInfoSerializer(serializers.ModelSerializer):
    group = serializers.HyperlinkedIdentityField(view_name='gp',lookup_field='group_id',lookup_url_kwarg='pk') # 反向生成url
    class Meta:
        model = models.UseInfo
        fields = ['id','username','password','group','roles']
        # 深度
        depth = 1 # 0 ~ 10


class UserInfoView(APIView):

    def get(self, request, *args, **kwargs):
        users = models.UseInfo.objects.all()
        ser = UserInfoSerializer(instance=users,many=True,context={
     'request': request})
        # print(ser)
        # UserInfoSerializer(context={'request': < rest_framework.request.Request: GET
        # '/api/userinfo/' >}, instance = < QuerySet[ < UseInfo: UseInfo
        # object(1) >, < UseInfo: UseInfo
        # object(2) >] >, many = True):
        # id = IntegerField(label='ID', read_only=True)
        # username = CharField(max_length=32, validators=[ < UniqueValidator(queryset=UseInfo.objects.all()) >])
        # password = CharField(max_length=64)
        # group = HyperlinkedIdentityField(lookup_field='group_id', lookup_url_kwarg='pk', view_name='gp')
        # roles = NestedSerializer(many=True, read_only=True):
        # id = IntegerField(label='ID', read_only=True)
        # title = CharField(max_length=32)
        ret = json.dumps(ser.data, ensure_ascii=False)
        return HttpResponse(ret)

    def post(self,request, *args, **kwargs):

        print(request.data)

        return HttpResponse("提交数据")

class GroupSerializer(serializers.ModelSerializer):

    class Meta:
        model = models.UserGroup
        fields = "__all__"

class GroupView(APIView):

    def get(self, request, *args, **kwargs):
        pk = kwargs.get('pk')
        obj = models.UserGroup.objects.filter(pk=pk).first()

        ser = GroupSerializer(instance=obj,many=False)
        ret = json.dumps(ser.data,ensure_ascii=False)
        return HttpResponse(ret)
# ===============================验证======================================
class UserGroupSerializer(serializers.Serializer):
    title = serializers.CharField(error_messages={
     
        'required': "标题不能为空"
    })

    # def validate_title(self,value):
        # print(value) # alex
        # return value # 要么返回值,要么直接报错
    #     from rest_framework import exceptions
    #     raise exceptions.ValidationError('看你不顺眼')

class UserGroupView(APIView):

    def post(self, request, *args, **kwargs):
        print(request.data)
        ser = UserGroupSerializer(data=request.data)
        if ser.is_valid():
            print(ser.validated_data) #字典
        else:
            print(ser.errors)
        return HttpResponse("提交数据")
#=======================================分页==============================

from api.utils.serializsers.pager import PagerSerializers
from rest_framework.response import Response
from rest_framework.pagination import PageNumberPagination,LimitOffsetPagination,CursorPagination

# 第一种分页
class MyPageNumberPagination(PageNumberPagination):
    page_size = 2 #每页的数据数量
    page_size_query_param = 'page_size' #自定也数量 url:http://127.0.0.1:8000/api/pager1/?page=2&size=3
    max_page_size = 5 # 最大为5  限制
    page_query_param = 'page'  # 页码

class Pager1View(APIView):
    def get(self, request, *args, **kwargs):
        # 获取所有数据
        roles = models.Role.objects.all()
        # 创建分页对象
        # pg = PageNumberPagination()
        pg = MyPageNumberPagination()# 自定义
        # 在数据库中获取分页数据
        pager_roles = pg.paginate_queryset(queryset=roles,request=request,view=self)
        # 对数据进行序列化
        ser = PagerSerializers(instance=pager_roles,many=True)
        # return pg.get_paginated_response(ser.data)
        return Response(ser.data)
# 第二种分页
class MyLimitOffsetPagination(LimitOffsetPagination):
    default_limit = 2 # 默认2条
    limit_query_param = 'limit'
    offset_query_param = 'offset'
    max_limit = 5

class Pager2View(APIView):

    def get(self,request,*args,**kwargs):
        # 获取所有数据
        roles = models.Role.objects.all()
        # 创建分页对象

        pg = MyLimitOffsetPagination()  # 自定义
        # 在数据库中获取分页数据
        pager_roles = pg.paginate_queryset(queryset=roles, request=request, view=self)
        # 对数据进行序列化
        ser = PagerSerializers(instance=pager_roles, many=True)
        # return pg.get_paginated_response(ser.data)
        return Response(ser.data)

# 第三种分页

class MyCursorPagination(CursorPagination):
    page_size = 2
    cursor_query_param = 'cursor'
    ordering = 'id'
    page_size_query_param = None
    max_page_size = None

class Pager3View(APIView):

    def get(self,request,*args,**kwargs):
        # 获取所有数据
        roles = models.Role.objects.all()
        # 创建分页对象

        pg = MyCursorPagination()  # 自定义
        # 在数据库中获取分页数据
        pager_roles = pg.paginate_queryset(queryset=roles, request=request, view=self)
        # 对数据进行序列化
        ser = PagerSerializers(instance=pager_roles, many=True)
        return pg.get_paginated_response(ser.data)
        # return Response(ser.data)

#==========================视图=========================

from rest_framework.generics import GenericAPIView
from api.utils.serializsers.pager import PagerSerializers


# 第一种:无用
class V1View(GenericAPIView):
    queryset = models.Role.objects.all()
    serializer_class = PagerSerializers
    pagination_class = PageNumberPagination

    def get(self,request,*args,**kwargs):
        # 获取数据
        roles = self.get_queryset() #models.Role.objects.all()
        # 分页
        pager_roles = self.paginate_queryset(roles)

        ser = self.get_serializer(instance=pager_roles,many=True)

        return Response(ser.data)
# 第二种 跟上面的功能一模一样,只是改了as_view方法,请求方式自定义(该函数名)
from rest_framework.viewsets import GenericViewSet

class V2View(GenericViewSet):

    def list(self,request,*args,**kwargs):# 等于get

        return Response("xxx")

    def xxx(self,request,*args,**kwargs):

        return Response("xx")

# 第三种

from rest_framework.viewsets import ModelViewSet
from rest_framework.mixins import ListModelMixin,CreateModelMixin
class V3View(ListModelMixin,CreateModelMixin,GenericViewSet):
    queryset = models.Role.objects.all()
    serializer_class = PagerSerializers
    pagination_class = PageNumberPagination

# 第四种
class V4View(ModelViewSet):
    queryset = models.Role.objects.all()
    serializer_class = PagerSerializers
    pagination_class = PageNumberPagination


# 渲染器
from rest_framework.renderers import JSONRenderer,BrowsableAPIRenderer,AdminRenderer
                                                                        #表格
class TestView(APIView):
    # renderer_classes = [JSONRenderer,BrowsableAPIRenderer]

    def get(self,request,*args,**kwargs):
        roles = models.Role.objects.all()
        # 创建分页对象
        pg = MyCursorPagination()  # 自定义
        # 在数据库中获取分页数据
        pager_roles = pg.paginate_queryset(queryset=roles, request=request, view=self)
        # 对数据进行序列化
        ser = PagerSerializers(instance=pager_roles, many=True)
        return Response(ser.data)

有点乱,其中PagerSerializers类在其他文件,视图就是视图文件,其他写配置文件,我这里的路径是api/utils/serializsers/pager.py:

from rest_framework import serializers
from api import models
class PagerSerializers(serializers.ModelSerializer):
    class Meta:
        model = models.Role
        fields = "__all__"

settings.py 全局配置

REST_FRAMEWORK = {
     
    "DEFAULT_PARSER_CLASSES": ['rest_framework.parsers.JSONParser','rest_framework.parsers.FormParser'],
    "PAGE_SIZE": 2,
    "DEFAULT_RENDERER_CLASSES": [
        'rest_framework.renderers.JSONRenderer',
        # 'rest_framework.BrowsableAPIRenderer'
    ]
}

你可能感兴趣的:(django,python,restful)