将None传递给DRF SerializerField的to_representation

时间:2017-09-13 15:11:01

标签: python django django-rest-framework django-serializer

我有以下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可以返回None,我希望使用to_representation方法将其转换为空字符串。但是,当我使用序列化程序解析此无值时,它甚至不会输入to_representation方法并立即返回None。我还应该更改为to_representation使用方法None

1 个答案:

答案 0 :(得分:1)

默认情况下,序列化程序的to_representation方法跳过带无值的字段(请参阅source)。

您可以编写mixin类来覆盖默认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):  
    ...