我有一个包含以下内容的 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字段的代码路径。
到目前为止我尝试过的:
唯一看起来相关的答案实际上并没有产生与 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
被声明为 a django.db.DateTimeField
,但如果我尝试类似的事情,LogEntry.timestamp.to_representation(log_entry.timestamp)
它会失败:
AttributeError: 'DeferredAttribute' 对象没有属性 'to_representation'
狐的传说
相关分类