drf序列化组件

Posted liweiwei0307

tags:

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

models

from django.db import models


# Create your models here.

class Book(models.Model):
    nid = models.AutoField(primary_key=True)
    name = models.CharField(max_length=32)
    price = models.DecimalField(max_digits=5, decimal_places=2)
    publish_date = models.DateField()

    publish = models.ForeignKey(to=Publish, to_field=nid, on_delete=models.CASCADE)
    authors = models.ManyToManyField(to=Author)

    def __str__(self):
        return self.name


class Author(models.Model):
    nid = models.AutoField(primary_key=True)
    name = models.CharField(max_length=32)
    age = models.IntegerField()
    author_detail = models.OneToOneField(to=AuthorDatail, to_field=nid, unique=True, on_delete=models.CASCADE)


class AuthorDatail(models.Model):
    nid = models.AutoField(primary_key=True)
    telephone = models.BigIntegerField()
    birthday = models.DateField()
    addr = models.CharField(max_length=64)


class Publish(models.Model):
    nid = models.AutoField(primary_key=True)
    name = models.CharField(max_length=32)
    city = models.CharField(max_length=32)
    email = models.EmailField()

    def __str__(self):
        return self.name

    def test(self):
        return self.email

views

from django.shortcuts import render
from django.http import JsonResponse
# Create your views here.
from rest_framework.views import APIView
from app01 import models
from app01.myser import BookSerializer


class Books(APIView):
    def get(self, request, *args, **kwargs):
        book = models.Book.objects.all()
        book_ser = BookSerializer(book, many=True)
        print(book_ser.data)
        return JsonResponse(book_ser.data, safe=False)

myser

from rest_framework import serializers


class AuthorSerializer(serializers.Serializer):
    name = serializers.CharField()
    age = serializers.CharField()
    telephone = serializers.CharField(source=author_detail.telephone)
    

# class BookSerializer(serializers.Serializer):
#     # 可以用source修改别名,如果不指定source,字段必须对应起来,如果指定了source,字段可以任意命名
#     xx = serializers.CharField(source=‘name‘)
#     price = serializers.CharField()
#     sb = serializers.CharField(source=‘publish.city‘)
#source 可以指定字段,也可也指定方法,publish.test这是个方法,会执行该方法,并拿到返回结果
#     test = serializers.CharField(source=‘publish.test‘)
#     publish_id = serializers.CharField()

#     # SerializerMethodField,可以指定一个方法
#     # publish=serializers.SerializerMethodField()
#     # # 方法名:叫get_字段名,要传参数,参数是:当前book对象
#     # def get_publish(self,obj):
#     #     # obj 是当前book对象0
#     #     dic={‘name‘:obj.publish.name,‘email‘:obj.publish.email}
#     #     return dic

#     authors=serializers.SerializerMethodField()
#     # def get_authors(self,book):
#     #     #拿到这本书的所有作者
#     #     aus=book.authors.all()
#     #     # 拼出一个列表,列表中套字典,每个字典是一个作者
#     #     ll=[]
#     #     for a in aus:
#     #         ll.append({‘name‘:a.name,‘age‘:a.age})
#     #     return ll
#     def get_authors(self,book):
#         #拿到这本书的所有作者
#         aus=book.authors.all()
#         # 可以继续用序列化类,来处理
#         auth_ser=AuthorSerializer(aus,many=True)
#         return auth_ser.data
from ap01.models import Book


# class BookSerializer(serializers.ModelSerializer):
#     # 必须写一个内部类,名字叫Meta
#     class Meta:
#         model = Book
#         fields = ‘__all__‘
#     # 重写属性
#     publish = serializers.CharField(source=‘publish.name‘)
#     authors = serializers.SerializerMethodField()
#     def get_authors(self, book):
#         # 拿到这本书的所有作者
#         aus = book.authors.all()
#         # 可以继续用序列化类,来处理
#         auth_ser = AuthorSerializer(aus, many=True)
#         return auth_ser.data


class BookSerializer(serializers.ModelSerializer):
    # 必须写一个内部类,名字叫Meta
    class Meta:
        model = Book
        # fields = ‘__all__‘
        # 指定只取这两个字段
        fields = [nid,name]
        # 去掉指定的字段
        # exclude=[‘publish‘,‘authors‘]
        # fields,跟exclude不能连用
        # 指定深度(官方建议小于10,我给你的建议小于3)
        # depth = 2

 

以上是关于drf序列化组件的主要内容,如果未能解决你的问题,请参考以下文章

第三章drf框架 - 序列化组件 | Serializer

drf 序列化组件

drf框架 - 序列化组件

DRF框架之 serializers 序列化组件

DRF之解析器组件及序列化组件

drf序列化组件