Django 设置 USE_TZ、TIME_ZONE 和 Django 休息框架

Django settings USE_TZ, TIME_ZONE and django rest framework

在Django教程中,有一句话描述如下。

TIME_ZONE

...

When USE_TZ is False, this is the time zone in which Django will store all datetimes. When USE_TZ is True, this is the default time zone that Django will use to display datetimes in templates and to interpret datetimes entered in forms.

...

当 django rest 框架从请求中获取原始日期时间数据时。然后 Django 会解释这个天真的日期时间以了解 TIME_ZONE 设置的本地日期时间?如果它是正确的,它是如何工作的?

提前致谢!

通常,在 serializer's DateTimeField(类似于表单字段)中解析请求时,在 DRF 中确定输入时区。

您可以控制此类输入的格式,甚至还有一个通用设置 DATETIME_INPUT_FORMATS,默认为 ['iso-8601']

这基本上意味着根据您的 Django 设置,输入既可以省略也可以使用 ISO-8601 format and the field will generally be able to determine whether to create an aware or naive datetime object 指定时区。

如果 timezone 属性设置为 None,它不会尝试将 naive datetime 转换为 aware ,也不会尝试如果属性不是 None.

,则将感知时区转换为原始时区

属性默认为TIME_ZONE if USE_TZ为True,否则为None;也可以在字段初始化中显式覆盖。

注意: 有人应该向 DRF 发送 PR 以记录此行为。

有关详细信息,请参阅 Django's time zone documentation

Then Django will interpret this naive datetime to aware local datetime of TIME_ZONE setting?

Django 在 template/form 级别使本机日期时间时区感知,因为 templates/forms 未在 Django restframework 视图中使用,Django 不会转换日期时间。

在 Django REST Framework 中,与 vanilla Django 一样,您必须设置 USE_TZTIME_ZONE 以激活时区设置,否则将不会进行转换。

但是直到v3.8.0(2018年5月发布),Django REST Framework只在解析阶段(json -> 模型)转换时区,而不是在渲染阶段(模型 -> json).这让很多人感到困惑。