" name="sm-site-verification"/>
侧边栏壁纸
博主头像
PySuper 博主等级

千里之行,始于足下

  • 累计撰写 227 篇文章
  • 累计创建 15 个标签
  • 累计收到 2 条评论

目 录CONTENT

文章目录
Web

Django Rest Framework

PySuper
2019-10-25 / 0 评论 / 0 点赞 / 45 阅读 / 0 字
温馨提示:
本文最后更新于2024-05-28,若内容或图片失效,请留言反馈。 所有牛逼的人都有一段苦逼的岁月。 但是你只要像SB一样去坚持,终将牛逼!!! ✊✊✊

将数据库数据序列化为前端所需要的格式,并返回

将前端发送的数据反序列化为模型类对象,并保存到数据库中

创建serializer对象

  • serializer构造方法:Serializer(instance=None, data=empty, **kwargs)
  • 序列化:将模型类对象传入instance参数
  • 反序列化:将要被反序列化的数据传入data参数
  • 额外数据:context参数serializer = AccountSerializer(account, context={"request": request})

通过context添加的数据,可以通过Serializer对象的context属性获取

序列化

from rest_framework import serializers
from app01 import models


class CommentSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Comment
        fields = "__all__"
        extra_kwargs = {
            "content": {"error_messages": {"required": "评论内容不能为空"}},
            "article": {"error_messages": {"required": "文章不能为空"}}
        }


class SchoolSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.School
        fields = "__all__"

视图

from rest_framework.views import APIView


class SchoolView(APIView):
    def get(self, request, *args, **kwargs):
        query_set = models.School.objects.all()
        ser_obj = app01_serializers.SchoolSerializer(query_set, many=True)
        return Response(ser_obj.data)


class SchoolDetail(APIView):
    def get(self, request, pk, *args, **kwargs):
        obj = models.School.objects.filter(pk=pk).first()
        ser_obj = app01_serializers.SchoolSerializer(obj)
        return Response(ser_obj.data)

使用rest formwork自带混合类方法

from rest_framework.generics import GenericAPIView  # 公共类
from rest_framework.mixins import ListModelMixin, RetrieveModelMixin, CreateModelMixin  # 混合类必须与公共类配合使用


class SchoolView(GenericAPIView, mixins.ListModelMixin):  # 查看学校列表
    queryset = models.School.objects.all()
    serializer_class = app01_serializers.SchoolSerializer

    def get(self, request, *args, **kwargs):
        return self.list(request, *args, **kwargs)


class SchoolDetail(GenericAPIView, mixins.RetrieveModelMixin, mixins.CreateModelMixin):  
    # 创建,与具体查出某一条记录
    queryset = models.School.objects.all()
    serializer_class = app01_serializers.SchoolSerializer

    def get(self, request, pk, *args, **kwargs):
        return self.retrieve(request, pk, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        return self.create(request, *args, **kwargs)

路由

url(r'school/$', views.SchoolView.as_view()),
url(r'school/(?P<pk>\d+)/$', views.SchoolDetail.as_view()),

使用rest formwork自带的通用类方法

from rest_framework.generics import GenericAPIView, ListCreateAPIView, RetrieveUpdateAPIVie


class SchoolView(ListCreateAPIView):  # 创建
    queryset = models.School.objects.all()
    serializer_class = app01_serializers.SchoolSerializer


class SchoolDetail(RetrieveUpdateDestroyAPIView):  # 更新
    queryset = models.School.objects.all()
    serializer_class = app01_serializers.SchoolSerializer

路由同上

使用rest formwork自带的封装所有放的类,代码量最少,功能最全

from rest_framework.viewsets import ModelViewSet  # 里面封装了操作的所有方法,增删改查查


class SchoolView(ModelViewSet):
    queryset = models.School.objects.all()
    serializer_class = app01_serializers.SchoolSerializer

路由

url(r'school/$', views.SchoolView.as_view(actions={
    "get": "list",
    "post": "create",
})),

url(r'school/(?P<pk>\d+)/$', views.SchoolView.as_view(actions={
    'get': 'retrieve',
    'put': 'update',
    'patch': 'partial_update',
    'delete': 'destroy'
})),

高级路由

from rest_framework.routers import DefaultRouter


router = DefaultRouter()
router.register(r'school', views.SchoolView)
urlpatterns += router.urls
0
  1. 支付宝打赏

    qrcode alipay
  2. 微信打赏

    qrcode weixin

评论区