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

Posted gyc-tzx

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django中rest_framework的APIView,序列化组件和视图组件相关的知识,希望对你有一定的参考价值。

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,序列化组件和视图组件的主要内容,如果未能解决你的问题,请参考以下文章

django rest_framework入门四-类视图APIView

Django rest_framework 实用技巧

Django 序列化器与 rest_framework 序列化器

python之Django rest_framework总结

Django Rest_Framework的简单介绍

如何在`django rest_framework test`的`APIClient`的标头中添加身份验证令牌