I have the following SerializerField:
class TimestampField(Field):
def to_representation(self, value):
if not value:
return ''
return value.timestamp()
And I use it like this in my serializer:
class ArticlePhotobookSerializer(ModelSerializer):
delivery_date_from = TimestampField()
delivery_date_to = TimestampField()
Now the getter delivery_date_to can return None, which I want to transform into an empty string using the to_representation method. however, when I use the Serializer to parse this None value, it doesn't even enter the to_representation method and immediately returns None. What should I change to also use the method to_representation for None?
By default serializer's
to_representationmethod skip fields with None value (see source).You can write mixin class to override default
to_representation:and use it in your serializers: