django多对多的序列化

from django.db import models
# Create your models here.

class Book(models.Model):
    title=models.CharField(max_length=32)
    price=models.IntegerField()
    pub_date=models.DateField()
    publish=models.ForeignKey("Publish")
    authors=models.ManyToManyField("Author")


    def __str__(self):
        return "app02 %s" % self.title

    class Meta:
        app_label='app02'


class Publish(models.Model):
    name=models.CharField(max_length=32)
    email=models.EmailField()


    def __str__(self):
        return "app02 %s" % self.name

    class Meta:
        app_label = 'app02'

class Author(models.Model):
    name=models.CharField(max_length=32)
    age=models.IntegerField()
    def __str__(self):
        return "app02 %s" %self.name

    class Meta:
        app_label = 'app02'

 对多序列化的两种方式,以下两种只适用于查取数据

class BookSerializers(serializers.Serializer):
    id=serializers.IntegerField()
    title=serializers.CharField()
    price=serializers.IntegerField()
    pub_date=serializers.DateField()
    # 多对一
    # source = "publish.email"
    # 可以指定model中的函数,也可以指定字段
    # 这种方式不使用于多对多,适用于一对一和多对一
    publish=serializers.CharField(source="publish.name",read_only=False)
    # 多对多
    authors=serializers.SerializerMethodField()
    # 钩子函数序列化,必须是以get_开头的
    def get_authors(self,obj):
        author=obj.authors.all()
        auth=AuthorSerializers(author,many=True)
        return auth.data
class BookModelSerializers(serializers.ModelSerializer):
    class Meta:
        model=models.Book
        fields='__all__'

        # 多对多
    authors = serializers.SerializerMethodField()

    # 钩子函数序列化,必须是以get_开头的
    def get_authors(self, obj):
        author = obj.authors.all()
        auth = AuthorSerializers(author, many=True)
        return auth.data

猜你喜欢

转载自www.cnblogs.com/xzcvblogs/p/12310286.html