DRF十大组件

4.版本
版本控制

模型类设计
from django.db import models


# Create your models here.
class UserGroup(models.Model):
    title = models.CharField(max_length=32, verbose_name='用户组名')


class Role(models.Model):
    title = models.CharField(max_length=32, verbose_name="角色")


class UserInfo(models.Model):
    user_type_choices = (
        (1, "普通用户"),
        (2, "VIP"),
        (3, "SVIP")
    )
    user_type = models.IntegerField(choices=user_type_choices, verbose_name="用户类型")

    username = models.CharField(max_length=32, unique=True)
    password = models.CharField(max_length=256)

    group = models.ForeignKey(UserGroup, verbose_name="用户类型")
    roles = models.ManyToManyField(Role)


class UserToken(models.Model):
    user = models.OneToOneField(UserInfo)
    token = models.CharField(max_length=256)

5.解释器
解析器的作用就是服务端接收客户端传过来的数据,把数据解析成自己想要的数据类型的过程.(DRF比Django强大很多)

from rest_framework.parsers import JSONParser


class ParserView(APIView):
    # 允许用户发送json格式数据
        # 1. 支持请求头content-type:application/json
        # 2. 支持请求体{"name":"zs","age":20}
    parser_classes = [JSONParser]

    def post(self, request, *args, **kwargs):
        print(type(request._request))
        return HttpResponse("POST和Body")

6.序列化
编写视图


import json
from django.forms.models import model_to_dict
class RolesView(APIView):
    def get(self, request, *args, **kwargs):
        #dgango序列化方式一
        roles = models.Role.objects.all().values('id', 'title')
        roles = list(roles)
         ret = json.dumps(roles,ensure_ascii=False)

        # dgango序列化方式二
        # roles = models.Role.objects.all()
        # ret = []
        # for model in roles:
        #     data = model_to_dict(model)
        #     ret.append(data)
        # 
        # print(ret)
        # ret = json.dumps(ret,ensure_ascii=False)
        return HttpResponse(ret,content_type='application/json')

7.分页
自定义使用

#自定义分页类
class MyPageNumberPagination(PageNumberPagination):
    #每页显示多少个
    page_size = 3
    #默认每页显示3个,可以通过传入pager1/?page=2&size=4,改变默认每页显示的个数
    page_size_query_param = "size"
    #最大页数不超过10
    max_page_size = 10
    #获取页码数的
    page_query_param = "page"


class Pager1View(APIView):
    def get(self,request,*args,**kwargs):
        #获取所有数据
        roles = models.Role.objects.all()
        #创建分页对象,这里是自定义的MyPageNumberPagination
        pg = MyPageNumberPagination()
        #获取分页的数据
        page_roles = pg.paginate_queryset(queryset=roles,request=request,view=self)
        #对数据进行序列化
        ser = PagerSerialiser(instance=page_roles,many=True)
        return Response(ser.data)

8.视图
视图 ListModelMixin

from rest_framework.generics import GenericAPIView
from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import ListModelMixin


class MyView(ListModelMixin,GenericViewSet):
    queryset = models.Role.objects.all()
    serializer_class = PagerSerializer
    pagination_class = PageNumberPagination

    def list(self, request, *args, **kwargs):
        # 获取数据
        roles = self.get_queryset()
        # 进行分页
        pager_roles = self.paginate_queryset(roles)
        # 序列化
        ser = self.get_serializer(instance=pager_roles, many=True)
        return Response(ser.data)

9.路由
10.渲染器

你可能感兴趣的:(django)