如何在Django-Rest框架中使用SerializerMethodField以原始形式返回一个列表外键字段?

2024-06-01 06:26:52 发布

您现在位置:Python中文网/ 问答频道 /正文

型号:

class Author(models.Model):
  name = models.CharField()

class Book(models.Model):
  author = models.ForeignKey("Author")
  title = models.CharField()
  subtitle = models.CharField()

  def get_full_title(self):
        return "{title}: {subtitle}.".format(title=self.title, subtitle=self.subtitle)

查询集:

^{pr2}$

期望响应:

[
    {
        "id": 1,
        "name": "J. R. R. Tolkien",
        "books": [
            "The Hobbit: or There and Back Again",
            "The Fellowship of the Ring: being the first part of The Lord of the Rings.",
            "The Two Towers: being the second part of The Lord of the Rings.",
            "The Return of the King: being the third part of The Lord of the Rings."
        ]
    },
    {
        "id": 2,
        "name": "Peter Thiel",
        "books": [
            "The Diversity Myth: Multiculturalism and Political Intolerance on Campus.",
            "Zero to One: Notes on Startups, or How to Build the Future."
        ]
    }
]

这里的问题是,如果您在Authors.book_set列表上使用serializers.ListSerializer(),那么我将在该列表中得到一个包含所有字段的完整模型。在

如果您尝试使用serializers.SerializerMethodField,DRF将不允许您在多个结果上使用它。SerializerMethodField不支持选项many AKAserializers.SerializerMethodField(many=True)我在这里应该注意到,可以编写一个方法来循环处理结果并将它们累积到一个字符串中,但这限制了您进一步扩展这段代码。

p.S.我把这个问题贴出来作为参考,因为我在其他地方找不到答案。查看下面的答案了解更多详细信息。在

p.p.S.我知道托尔金写了4本以上的书。在


Tags: ofthenameselftitlemodelsclasscharfield
1条回答
网友
1楼 · 发布于 2024-06-01 06:26:52

首先,您需要创建一个自定义列表序列化程序,该方法将返回具有所需表示形式的字符串。在

class AutorBookSetSerializer(serializers.ListSerializer):

    def get_custom_repr(self, obj):
        return obj.get_full_title()

第二,您需要用一个新的字段"books"来包装常规模型序列化程序,而这个字段在初始模型中不存在。然后将新的序列化程序分配给该字段,并作为子项指定自定义的SerializerMethodField调用。在

^{pr2}$

为什么会有人需要这个?在

如果你不想让一个复杂的结构,你可以在里面定义一个复杂的结构。在

相关问题 更多 >