将 None 传递给 DRF SerializerField 的 to_representation

Pass None to DRF SerializerField's to_representation

我有以下 SerializerField:

class TimestampField(Field):
    def to_representation(self, value):
        if not value:
            return ''

        return value.timestamp()

我在序列化器中这样使用它:

class ArticlePhotobookSerializer(ModelSerializer):  
    delivery_date_from = TimestampField()
    delivery_date_to = TimestampField()

现在 getter delivery_date_to 可以 return None,我想使用 to_representation 方法将其转换为空字符串。但是,当我使用Serializer 解析这个None 值时,它甚至没有进入to_representation 方法并立即returns None。我应该更改什么才能将方法 to_representation 用于 None?

默认情况下,序列化程序的 to_representation 方法会跳过具有 None 值的字段(参见 source)。

你可以编写 mixin class 来覆盖默认值 to_representation:

class ToReprMixin(object):  
    def to_representation(self, instance):
        ret = OrderedDict()
        fields = [field for field in self.fields.values() if not field.write_only]

        for field in fields:
            try:
                attribute = field.get_attribute(instance)
            except SkipField:
                continue

            ret[field.field_name] = field.to_representation(attribute)

        return ret

并在您的序列化程序中使用它:

class ArticlePhotobookSerializer(ToReprMixin, ModelSerializer):  
    ...