django多对一和多对多的序列化
(以下方式只用于序列化,反序列化报错)
1.models表
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'
2.多对一和多对多的序列的方式(方式一)
class AuthorSerializers(serializers.Serializer):
name=serializers.CharField()
age=serializers.IntegerField()
class Publishser(serializers.Serializer):
name=serializers.CharField(max_length=32)
email=serializers.EmailField()
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)
# 多对一序列化多个值的写法
publish = Publishser()
# 多对多
authors=serializers.SerializerMethodField()
# 钩子函数序列化,必须是以get_开头的
def get_authors(self,obj):
author=obj.authors.all()
auth=AuthorSerializers(author,many=True)
return auth.data
3.多对一和多对多的序列的方式(方式二)
class AuthorSer(serializers.ModelSerializer): class Meta: model=models.Author fields='__all__' class Publishser(serializers.ModelSerializer): class Meta: model=models.Publish fields='__all__' class BookModelSerializers(serializers.ModelSerializer):
#多对一 publish = Publishser() # 多对多 authors = serializers.SerializerMethodField() # 钩子函数序列化,必须是以get_开头的 def get_authors(self, obj): author = obj.authors.all() auth = AuthorSerializers(author, many=True) return auth.data class Meta: model=models.Book fields='__all__'