【问题标题】:change datetime field to return unix timestamp in django rest framework更改日期时间字段以在 django rest 框架中返回 unix 时间戳
【发布时间】:2021-02-19 22:26:42
【问题描述】:
我想获取以毫秒或秒为单位的时间戳,以便将其转换为前端的 DateTime javascript 对象。如果有办法转换这种格式
"timestamp" : "2020-11-06T10: 51: 10Z" 到 javascript DateTime 对象告诉我。如果我需要为 DateTime 使用单独的序列化器,如何在序列化器中使用序列化器?
【问题讨论】:
标签:
reactjs
datetime
serialization
django-rest-framework
timestamp
【解决方案1】:
如果您不喜欢默认的字符串表示,您可以在序列化程序中覆盖 to_representation 方法:
class YourSerializer(serializers.ModelSerializer):
class Meta:
model = YourModel
fields = ['id', 'your_datetime_field']
def to_representation(self, instance):
formatted_datetime_field = instance.your_datetime_field.timestamp()
return {'id': instance.id,
'your_datetime_field': instance.formatted_datetime_field}
这将为您提供 Unix 时间,以秒为单位。 JavaScript 的 Date 对象以毫秒为单位工作,因此您可以将结果乘以 1000 以使其在前端工作。我认为在 JS 端进行转换更有意义,但这取决于你。