【问题标题】:Custom Django Rest Framework Serializer Field not running `to_representation()` if value is null如果值为 null,则自定义 Django Rest Framework 序列化程序字段不运行`to_representation()`
【发布时间】:2019-01-18 16:00:22
【问题描述】:

我想要一个自定义(只读)序列化器字段,如果它是None,它会替换序列化值。我以为我可以覆盖to_representation(),但这似乎没有运行。这是一些代码:

models.py:

class Book(models.Model):
  title = models.CharField(max_length=255)
  rating = models.IntegerField(null=True)

序列化器:

class ReplaceableSerializerField(serializers.ReadOnlyField):

  def to_representation(self, value):
    if value is None:
      return "this book sucks"
    return value

class BookSerializer(serializers.ModelSerializer):

  class Meta:
    model = Book
    fields = ("title", "rating",)

  rating = ReplaceableSerializerField(allow_null=True)

如果我然后执行以下操作:

hamlet = Book(title="Hamlet")
BookSerializer(instance=hamlet).data

我收到以下回复:

{'title': 'Hamlet', 'rating', None}

注意评分是None,而不是“这本书很烂”。

知道如何强制to_representation() 在空字段上运行吗?

【问题讨论】:

  • 您能否在覆盖的 to_representation 中首先以 super().to_representation() 的身份进行 super_call。
  • @Shakil - 谢谢。这没有任何效果(ReadOnlyField.to_representation() 只是返回“值”)。
  • 可能听起来很愚蠢,你能不能试试 value == None 而不是 value is None。
  • @Shakil - 同样,这没有效果。

标签: django serialization django-rest-framework


【解决方案1】:

据我从implementation 了解到,如果值为None,则不会调用to_representation 方法。所以为了避免这个问题,我认为你可以使用SerializerMethodField。你可以这样使用它:

class BookSerializer(serializers.ModelSerializer):
  rating = serailizer.SerializerMethodField()

  class Meta:
    model = Book
    fields = ("title", "rating",)

  def get_rating(self, obj):
      if obj.rating == None:
         return "Something"
      return obj.rating

【讨论】:

  • 是的,我最后就是这么做的。但它仍然让我烦恼。
  • 这是一个问题,因为 SerializerMethodField 是只读的。通常你覆盖 Field 以获得一个可读写的自定义字段,如果 to_representation 没有在空值上运行,你不能将空值转换为例如 False :/
  • 也许我们应该为它创建一个问题
  • 我也有一个用例。是否为此创建了问题?如果是这样,你能提供一个链接吗?如果没有,“我们”如何做到这一点?
【解决方案2】:

我的解决方法是重写 get_attribute(self, instance) 方法。

def get_attribute(self, instance):
    value = getattr(instance, self.source)
    if value is None:
        return "this book sucks"
    return value

djangorestframework 3.12.4

【讨论】:

    猜你喜欢
    • 2015-06-29
    • 1970-01-01
    • 1970-01-01
    • 2017-03-10
    • 2016-11-28
    • 1970-01-01
    • 1970-01-01
    • 2017-06-07
    • 1970-01-01
    相关资源
    最近更新 更多