Django中rest_framework的APIView,序列化组件和视图组件

2021-05-29 12:02

阅读:714

标签:ram   else   lte   framework   eric   serial   objects   request   response   

url

 

urlpatterns = [
    url(r‘^admin/‘, admin.site.urls),
    url(r‘^books/$‘, views.BookHandle.as_view()),
    url(r‘^books/(\d+)‘, views.GetBookHandle.as_view()),

    url(r‘^publishs/$‘, views.PublishHandel.as_view()),
]

 

  

views

#####################################################
# request => Request => request.data  (APIView执行流程,且封装了一些组件)
from rest_framework.views import APIView
from rest_framework import serializers     # 序列化组件
from rest_framework.response import Response    # 给前端返回消息
from app01 import models

# get,post,delete方法 用到的序列化组件
class BookSerializer(serializers.ModelSerializer):

    class Meta:
        model = models.Book
        fields = ‘__all__‘


# get方法 用到的序列化组件
class BookSerializer_get(serializers.ModelSerializer):

    class Meta:
        model = models.Book
        fields = ‘__all__‘  # 拿到Book表的所有字段[‘price‘,‘title‘]

        # 除了Book表的price字段(拿到其他所有字段),exclude不能和fields同时用
        # exclude = (‘price‘,)

    #针对多对一字段的序列化,里面有source=‘‘,里面写关联的字段名字.被关联表的字段
    publish = serializers.CharField(max_length=32, source=‘publish.name‘)

    #针对多对多字段的序列化
    authors = serializers.SerializerMethodField()
    # 多对多字段名前面加get_ 自动执行该方法.传入的参数就是Book表的model对象
    def get_authors(self,obj):
        lis = []
        authors_obj = obj.authors.all()
        for author_obj in authors_obj:
            dic = {}
            dic[‘name‘] = author_obj.name
            lis.append(dic)
        return  lis

# 应用序列化组件
class BookHandle(APIView):

    def get(self,request):
        book_list_obj = models.Book.objects.all()
        # get方法时,自定义序列化参数是查询的到的表的model对象,many

        msg = BookSerializer_get(book_list_obj,many=True)
        return Response(msg.data)

    def post(self,request):
        # post,put方法时,这个自定义序列里面的参数是data=request.data,many
        msg = BookSerializer(data=request.data,many=False)
        if msg.is_valid():
            msg.save()  #create
            return Response(msg.data)
        else:
            return Response(msg.errors)

class GetBookHandle(APIView):

    def put(self,request,id):
        book_obj = models.Book.objects.filter(pk=id).first()
        msg = BookSerializer(data=request.data,many=False,instance=book_obj)
        if msg.is_valid():
            msg.save()
            return Response(msg.data)
        else :
            return Response(msg.errors)

    def delete(self,request,id):
        models.Book.objects.filter(pk=id).delete()
        return Response(‘‘)

    def get(self,request,id):
        book_obj = models.Book.objects.filter(pk=id).first()

        msg = BookSerializer_get(book_obj,many=False)
        return Response(msg.data)

#################视图组件##############

class PublishSerializer(serializers.ModelSerializer):

    class Meta:
        model = models.Publish
        fields = ‘__all__‘

from rest_framework.mixins import ListModelMixin
from rest_framework import generics

class PublishHandel(ListModelMixin,generics.GenericAPIView):
    queryset = models.Publish.objects.all()
    serializer_class = PublishSerializer

    def get(self,request):
        return self.list(request)

  

 

Django中rest_framework的APIView,序列化组件和视图组件

标签:ram   else   lte   framework   eric   serial   objects   request   response   

原文地址:https://www.cnblogs.com/gyc-tzx/p/11096260.html


评论


亲,登录后才可以留言!