phy*_*ion 2 python django django-serializer django-rest-framework
我有以下 SerializerField:
class TimestampField(Field):
def to_representation(self, value):
if not value:
return ''
return value.timestamp()
Run Code Online (Sandbox Code Playgroud)
我在我的序列化程序中像这样使用它:
class ArticlePhotobookSerializer(ModelSerializer):
delivery_date_from = TimestampField()
delivery_date_to = TimestampField()
Run Code Online (Sandbox Code Playgroud)
现在 getterdelivery_date_to可以返回 None,我想使用该to_representation方法将其转换为空字符串。但是,当我使用 Serializer 解析这个 None 值时,它甚至没有进入该to_representation方法并立即返回None. 我应该怎么改也使用该方法to_representation的None?
默认情况下,序列化程序的to_representation方法会跳过具有 None 值的字段(请参阅源代码)。
您可以编写 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
Run Code Online (Sandbox Code Playgroud)
并在您的序列化程序中使用它:
class ArticlePhotobookSerializer(ToReprMixin, ModelSerializer):
...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1268 次 |
| 最近记录: |