简体   繁体   English

如何嵌套两个具有相同模型的序列化器

[英]How to nest two serializers with same model

I have two serializers with same model. 我有两个型号相同的序列化器。 I want to nest them. 我要嵌套它们。

Unfortunately this approach does not work: 不幸的是,这种方法不起作用:

class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        fields = ['name', 'word_count']


class BetterBookSerializer(serializers.ModelSerializer):
    book = BookSerializer(many=False)

    class Meta:
        model = Book
        fields = ('id', 'book')

Expected result: 预期结果:

{
  "id": 123,
  "book": {
    "name": "book_name",
    "word_count": 123
  }
}

Use source=* instead of many=True as 使用source=*而不是many=True作为

class BetterBookSerializer(serializers.ModelSerializer):
    book = BookSerializer(source='*')

    class Meta:
        model = Book
        fields = ('id', 'book')

From the doc , 从文档中

The value source='*' has a special meaning, and is used to indicate that the entire object should be passed through to the field. source='*'具有特殊含义,用于表示应将整个对象传递给该字段。 This can be useful for creating nested representations, or for fields which require access to the complete object in order to determine the output representation. 这对于创建嵌套表示或对于需要访问完整对象才能确定输出表示的字段很有用。

You can achieve the desired output like this: 您可以像这样实现所需的输出:

class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        fields = ['name', 'word_count']

class BetterBookSerializer(serializers.ModelSerializer):
    book = serializers.SerializerMethodField(read_only=True)

    class Meta:
         model = Book
         fields = ('id', 'book')

    def get_book(self, obj):
         return BookSerializer(obj).data

Small Update: Although my approach to solve your problem works just fine, the answer from @JPG mentioning source='*' option is a good way to go. 小更新:尽管我解决问题的方法很好,但是@JPG提到source='*'选项的答案是一个不错的选择。 In that way you can easily use the nested serializer when creating new object. 这样,您可以在创建新对象时轻松使用嵌套的序列化程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM