DAY97 - Rest Framework(二)- 序列化组件之Serializer和ModelSerializer

一、序列化组件之Serializer

from django.http import JsonResponse
from rest_framework.views import APIView
from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework import serializers
from app01 import models

class AuthorSerializers(serializers.Serializer):
    name = serializers.CharField(max_length=32)
    sex = serializers.CharField(max_length=32)
    
    
class BookSerializers(serializers.Serializer):
    name = serializers.CharField(max_length=32)
    # source 可以指定字段,可以对字段重命名,不使用则前面的变量名必须和表一样
    book_price = serializers.CharField(max_length=32, source='price')
     
    # 跨表查询:查询书本的出版社名
    # 方式一
    # 使用该方法必须重写Publish表的__str__方法,不然显示的是publish对象
    # def __str__(self):
    #    return self.name
    # 显示 "publish": "北京出版社"
    publish = serializers.CharField()
      
        
    # 方式二
    # source可以指定字段,那么可以使用基于对象的跨表查询来引用publish.name
    publish = serializers.CharField(source='publish.name')
    
    
	# 方式三
    # source不仅可以指定字段,还可以指定方法
    # def test(self):
    #     return self.name
    publish = serializers.CharField(source='publish.test')

    
    # 方法四
    # SerializerMethodField() 可以指定一个方法
    publish = serializers.SerializerMethodField()
    # 方法名必须是get_字段名,传入参数obj:当前的book对象
    def get_publish(self,obj):
        ll={'name':obj.publish.name,'email':obj.publish.email}
        return ll
    
    # 方法内部也可以使用序列化组件
    authors = serializers.SerializerMethodField()
    def get_authors(self,obj):
        # 拿到这本书的所有作者
        authors = obj.authors.all()
        author_ret = AuthorSerializers(authors, many=True)
        return author_ret.data
    
    
class Books(APIView):
    def get(self, request, *args, **kwargs):
        books = models.Book.objects.all()
        ret = BookSerializers(books, many=True)
        return JsonResponse(ret.data, safe=False)

二、序列化组件之ModelSerializer

from django.http import JsonResponse
from rest_framework.views import APIView
from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework import serializers
from app01 import models

class AuthorSerializers(serializers.Serializer):
    name = serializers.CharField(max_length=32)
    sex = serializers.CharField(max_length=32)

class BookSerializers(serializers.ModelSerializer):
    # Meta是必须写的
    class Meta:
        # model:指定表
        model = models.Book
        # fields:显示的字段
        # 全部显示
        fields = '__all__'
        # 部分显示
        # fields = ['name','price']
        # exclude:不显示的字段,exclude和fields不能一块使用
        # exclude=['publish','authors']
        # depth:跨表显示的深度,不写默认为0,一般最好小于3
        # 比如depth=1,就显示作者信息和出版社信息;depth=2,作者详情表也显示
        # depth=1

    # 但是这样字段名就写死了,像出版社和作者就只显示ID
    # 可以重写字段
    publish = serializers.CharField(source='publish.name')
    authors = serializers.SerializerMethodField()

    def get_authors(self, obj):
        # 拿到这本书的所有作者
        authors = obj.authors.all()
        author_ret = AuthorSerializers(authors, many=True)
        return author_ret.data


class Books(APIView):
    def get(self, request, *args, **kwargs):
        books = models.Book.objects.all()
        ret = BookSerializers(books, many=True)
        return JsonResponse(ret.data, safe=False)
posted @ 2018-12-11 17:11  藏岚  阅读(202)  评论(2编辑  收藏  举报