有了django rest框架,我有两个针对两个不同模型的序列化器。可以说,模型是作者和书本。作者模型具有以下字段:名称,地址,电话,电子邮件,描述和created_at,而书中具有以下字段:名称,出版商名称,类型,描述,created_at和author(作者模型的外键)。
现在,我已经为Author和Book定义了序列化器:
class BookSerializer(serializers.Serializer):
class Meta:
model = Book
exclude = ['created_at']
class AuthorSerializer(serializers.Serializer):
books = BookSerializer(many=True,required=False,null=True)
class Meta:
model = Author
exclude = ['created_at']
当前模式给出了Book序列化器的返回值,例如:
{
"id":1,
"name":"Book_name",
"publisher_name":"Publisher",
"genre":"g",
"description":"Book description",
"author":1
}
authorserializer的返回是:
{
"id":1,
"address":"Address",
"phone":9812312312,
"email":"email@email.c",
"description":"this is description",
"books": [
{
"id":1,
"name":"Book_name",
"publisher_name":"Publisher",
"genre":"g",
"description":"Book description",
"author":1
}
]
}
问题是我不希望Authorserializer的归还书中的所有详细信息,而是要排除描述和体裁。 该怎么做?
答案 0 :(得分:0)
您将需要为Books创建一个新的序列化器。也许将其称为BookSummarySerializer:
class BookSummarySerializer(serializers.Serializer):
class Meta:
model = Book
exclude = ['created_at', 'description', 'genre']
class AuthorSerializer(serializers.Serializer):
books = BookSummarySerializer(many=True,required=False,null=True)
class Meta:
model = Author
exclude = ['created_at']
答案 1 :(得分:0)
为同一模型定义了多个序列化器以嵌套在不同的序列化器中之后,我想出了一个简单的动态模型序列化器,可以在需要的地方内联创建。</ p>
class InlineModelSerializer(serializers.ModelSerializer):
"""
Used to dynamically create simple model serializers inline,
mostly nested as fields in other serializers
"""
def __init__(self, fields, model, **kwargs):
"""
:param fields: The fields to be included
:param model: The model class for the serializer
:type fields: tuple
"""
self.Meta = type('Meta', (), {'model': model, 'fields': fields})
super(InlineModelSerializer, self).__init__(**kwargs)
然后您可以在AuthorSerializer
或任何需要它的地方使用它,如下所示:
books = InlineModelSerializer(
model=Book,
fields=('id', 'name'),
many=True,
required=False,
allow_null=True
)
如果您必须在嵌套序列化器中重写一个方法,那么这当然将不起作用,因此它主要用于简单的用例,而不适用于复杂的可写嵌套序列化器。
希望这会有所帮助