【发布时间】:2019-02-14 21:42:37
【问题描述】:
我有一个 Django REST Framework 序列化程序,其中包含以下内容:
from rest_framework import serializers
class ThingSerializer(serializers.ModelSerializer):
last_changed = serializers.SerializerMethodField(read_only=True)
def get_last_changed(self, instance: Thing) -> str:
log_entry = LogEntry.objects.get_for_object(instance).latest()
representation: str = serializers.DateTimeField('%Y-%m-%dT%H:%M:%SZ').to_representation(log_entry.timestamp)
return representation
这是有问题的,因为如果日期时间格式发生变化,它将与所有其他 datetimes 不同。我想重用 DRF 用来序列化其他 datetime 字段的代码路径。
到目前为止我已经尝试过:
- 唯一看起来相关的 answer 实际上并没有产生与 DRF 相同的结果(它包括毫秒,而 DRF 没有),大概是因为它使用的是 Django 而不是 DRF 序列化程序。
-
rest_framework.serializers.DateTimeField().to_representation(log_entry.timestamp)、rest_framework.fields.DateTimeField().to_representation(log_entry.timestamp)和rest_framework.fields.DateTimeField(format=api_settings.DATETIME_FORMAT).to_representation(log_entry.timestamp)也不起作用;他们产生具有微秒精度的字符串。我已经用调试器验证了 DRF 在序列化其他字段时调用后者,所以我不明白为什么它会在我的情况下产生不同的结果。 -
LogEntry.timestamp被声明为django.db.DateTimeField,但如果我尝试LogEntry.timestamp.to_representation(log_entry.timestamp)之类的东西,它会严重失败:AttributeError: 'DeferredAttribute' 对象没有属性 'to_representation'
【问题讨论】:
标签: python django django-rest-framework