我们可以有没有时区的Django DateTimeField吗? [英] Can we have Django DateTimeField without timezone?
问题描述
我已经搜索过此内容,但找不到任何注释或教程。
I have searched for this, and could not find any notes or tutorials.
推荐答案
设置 USE_TZ = True
(请参见 USE_TZ 获取更多信息),Django将日期和时间信息存储在数据库的UTC中,否则它将存储原始日期时间(不带时区的日期时间)。
When you set USE_TZ = True
(see USE_TZ for more info) in your settings, Django stores date and time information in UTC in the database otherwise it will store naive date time (date time without timezone).
django-admin startproject
创建的默认 settings.py
文件包括 USE_TZ = True
为方便起见。
The default settings.py
file created by django-admin startproject
includes USE_TZ = True
for convenience.
因此,必须在设置中设置 USE_TZ = False
以避免附加时区。
So you have to set USE_TZ = False
in your settings to avoid attaching timezone.
注意:但是,您不能仅为特定字段分离时区。按照上面的建议,您可以从整个数据库中分离出时区,所以我猜想最好使用CharField来存储不带时区的日期。
NOTE: However you cannot detach timezone only for a particular field. By following my suggestion above, you detach timezone from the entire database, so my guess is that it's better to use a CharField to store date without timezone.
您可以尝试覆盖默认保存处理程序,并在保存之前从DatetimeField中删除时区通过为模型定义保存方法将其存入数据库:
You can try to override the default save handler and remove the timezone from DatetimeField before saving the item into the database, by defining a save method for your model:
def save(self, *args, **kwargs):
self.datetime_field = self.datetime_field.replace(tzinfo=None)
super(MyModel, self).save(*args, **kwargs)
这篇关于我们可以有没有时区的Django DateTimeField吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!