从序列化器中的 DateTimeField 中删除 Z
有没有办法让我的序列化器默认打印日期时间字段,
2022-03-28T00:00:00+00:00
所示
2022-03-23T03:16:00Z
如下
return obj.time.isoformat()
Is there a way to make my serializer print the datetimefield by default like this
2022-03-28T00:00:00+00:00
Instead of this
2022-03-23T03:16:00Z
I get the first output when I do this
return obj.time.isoformat()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
原因
如果您查看
serializers.DateTimeField
中的django-rest-framework
代码,如果日期时间是 UTC 时区,则 UTC 偏移量 (+00:00
code>) 将被转换为Z
,可以看出 此处解决方案
如果您想要使其可重复使用
DateTimeField
,您需要创建一个继承自serializers.DateTimeField
的自定义序列化器DateTimeField
并重写to_representation
方法处理 django-rest-framework 中的代码并删除将 UTC 偏移字符串转换为 Z 的行。然后在序列化器中使用它而不是
serializers.DateTimeField
Extra
如果您想在
serializers.ModelSerializer
中使用它,您需要按照以下步骤ModelSerializer
继承自serializers.ModelSerializer
并设置serializer_field_mapping
属性,如下所示CustomModelSerializer
而不是serializers.ModelSerializer
。例如Cause
If you look into the code of
django-rest-framework
inserializers.DateTimeField
if datetime is UTC timezone, the UTC offset (+00:00
) will get converted toZ
as can be seen hereSolution
If you want to make it reusable for
DateTimeField
, you need to create a custom serializerDateTimeField
that inherits fromserializers.DateTimeField
and override theto_representation
method by coping codes fromdjango-rest-framework
and removing lines that convert UTC offset string toZ
.Then use this in your serializer instead of
serializers.DateTimeField
Extra
If you want to use it in
serializers.ModelSerializer
, you need to follow below stepsModelSerializer
that inherits fromserializers.ModelSerializer
and setserializer_field_mapping
attribute as followsCustomModelSerializer
instead ofserializers.ModelSerializer
. E.g.最简单的方法是在序列化器中指定所需的格式:
The simplest way to do it is to specify the format you want in your serializer: