我可以将单个 Django 模型字段拆分为多个 Django Rest Framework 序列化器字段吗?

Posted

技术标签:

【中文标题】我可以将单个 Django 模型字段拆分为多个 Django Rest Framework 序列化器字段吗?【英文标题】:Can I split a single Django model field into multiple Django Rest Framework serializer fields? 【发布时间】:2020-11-23 16:01:42 【问题描述】:

是否可以将单个 m2m Django 模型字段拆分为多个 DRF 序列化器字段?

考虑以下代码:

models.py:

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

class BookQuerySet(models.QuerySet):
  def good(self):
    return self.filter(is_good=True)

  def bad(self):
    return self.filter(is_good=False)

class Book(models.Model):
  objects = BookQuerySet.as_manager()

  title = models.CharField()
  author = models.ForeignKey(Author, related_name="books")
  is_good = models.BooleanField(default=False)

serializers.py:

class BookSerializer(serializers.ModelSerializer):
  class Meta:
    model = Book
    fields = ["title"]

class AuthorSerializer(serializers.ModelSerializer):
  class Meta:
    model = Author
    fields = ["name", "books"]

  books = BookSerializer(many=True)

我有什么办法实际上将“书籍”序列化为good_booksbad_books,但仍然让它们映射到Author 模型上的单个books 字段?

请记住,这些需要是可写的嵌套序列化器。

【问题讨论】:

【参考方案1】:

当然可以,定义一个 serializeMethodField

class AuthorSerializer(serializers.ModelSerializer):
  books = BookSerializer(many=True) # here you get all books
  good_books = serializers.serializeMethodField()
  bad_books = serializers.serializeMethodField()
  
  class Meta:
    model = Author
    fields = ["name", "books", "good_books", "bad_books"]

  def get_good_books(self, author):
      return BookSerializer(author.books.good()).data

  def get_bad_books(self, author):
      return BookSerializer(author.books.bad()).data

或:

class AuthorSerializer(serializers.ModelSerializer):
  books =  serializers.serializeMethodField()
  
  class Meta:
    model = Author
    fields = ["name", "books"]

  def get_books(self, author):
      # bad and good books in the same key
      # result like:
      # "books":  "bad_books": [....list], "good_books": [...list
      return 
         "good_books": BookSerializer(author.books.good()).data,
         "bad_books": BookSerializer(author.books.bad()).data,
      

【讨论】:

谢谢。我还能使用带有 SerializerMethodField 的自定义 BookSerializer 类(以及它使用的自定义 ListSerializer 类)吗(在这个小示例中我没有展示很多花哨的代码)?

以上是关于我可以将单个 Django 模型字段拆分为多个 Django Rest Framework 序列化器字段吗?的主要内容,如果未能解决你的问题,请参考以下文章

Django,当单个模型变大时模型拆分?

Django 多文件字段

将 Django 管理“添加”界面中的字段拆分为其组成字段

Django:如何覆盖 form.save()?

如何在django中为问题添加多个表单字段类型的选项?

如何在 django 模型中从一个字段添加多个输入