Django RuntimeWarning: DateTimeField 在我的 django python 模型中出现



我在模型中创建了一个带有日期时间字段的类,我认为该类在我的项目中导致错误

class Job(models.Model):
category_id = models.ForeignKey(Category, on_delete=models.CASCADE)
number_of_bids = models.IntegerField()
time_starting = models.DateTimeField()
time_ending = models.DateTimeField()

返回的错误如下所示

C:UsersUserAppDataLocalProgramsPythonPython37-32libsite-packagesdjango-2.1.1-py3.7.eggdjangodbmodelsfields__init__.py:1421: RuntimeWarning: DateTimeField Job.time_ending received a naive datetime (2018-10-25 10:03:58.889072) while time zone support is active.
RuntimeWarning)

任何修复提示

你正在将 Python 的日期时间值传递到你的模型中。

即这个

from datetime import datetime
datetime.now() # Incompatible with Python's DateTimeField directly

您需要做的是从from django.utils import timezone传递一个时区感知对象,如下所示

from django.utils import timezone
timezone.now() # Will fit right into DateTimeField in your model

引用文档朴素和感知的日期时间对象
Python 的datetime.datetime对象有一个可用于存储时区信息的tzinfo属性,表示为 datetime.tzinfo 子类的实例。当设置此属性并描述偏移量时,日期时间对象是感知的。否则,这是幼稚的。

您可以使用is_aware()is_naive()来确定日期时间是已知的还是未定的。

更多信息在这里

您传递的日期时间无法识别时区。 您必须将时区添加到日期时间字段。

如果使用python/django来保存时区:

from django.utils import timezone
timezone.now()

如果要序列化数据,则不要使用'2018-10-25 10:03:58.889072''2018-09-09T00:00:00Z'

最新更新