Django夹具DateTimeField运行时警告

17

我为我的 Django 项目设置了一些基本的测试数据。其中一个插入到数据库中的记录如下所示:

  {
    "model": "articles.article",
    "pk": 1,
    "fields": {
      "title": "Blackened Recordings Launches",
      "headline": "we're so psyched about our new adventure",
      "content": "<p>We like to make it a point here not to bore you with the not-so-exciting business aspects of making and sharing music, but we're so psyched about our new adventure that we just had to tell you about it as we officially launch our very own record label, Blackened Recordings.</p><p>Some of you, who have followed along throughout the years, are aware that in 1994 we renegotiated our contract with the Warner Music Group, which resulted in a joint venture with our record company for releasing all of our recordings including long form videos. Per that agreement, as of today we have taken ownership of all of our master recordings and Blackened Recordings will be the home of all of our current albums and videos along with all future releases including the December 10 release of the \"Quebec Magnetic\" DVD and Blu-ray.</p><p>You may have heard us say it once or twice or a thousand times before, but it's always been about us taking control of all things 'Tallica to give you 110% on every single level every single time. Forming Blackened Recordings is the ultimate in independence, putting us in the driver's seat of our own creative destiny. We're looking forward to making more music and getting it all out to you in our own unique way.</p>",
      "image": "examples/slide-03.jpg",
      "active": 1,
      "created_at": "2013-03-16 17:41:28"
    }
  },

这是相应的模型:

class Article(models.Model):
    """News article, displayed on homepage to attract users"""
    class Meta:
        db_table = 'article'
    title = models.CharField(max_length=64)
    headline = models.CharField(max_length=255)
    content = models.TextField()
    image = models.ImageField(upload_to = 'articles/', null=True, blank=True)
    active = models.BooleanField()
    created_at = models.DateTimeField()
    def __unicode__(self):
        return self.title

在插入夹具记录时,我收到以下警告:

/usr/local/lib/python2.7/dist-packages/django/db/models/fields/__init__.py:827: RuntimeWarning: DateTimeField received a naive datetime (2013-03-16 17:41:28) while time zone support is active.
  RuntimeWarning)

我不知道这里出了什么问题。我试图遵循这篇博客文章,但我已经安装了pytz并且在我的settings.py文件中有USE_TZ=True选项。

3个回答

30

实际上,解决方案已经深藏在Python文档中了,以下是引用:

当序列化一个已知的日期时间时,会包含UTC偏移,例如:

"2011-09-01T13:20:30+03:00"

这样的fixtures是完全被接受的,在我的情况下就是这样:

"2013-03-16T17:41:28+00:00"
"2013-03-17T23:36:12+00:00"
"2013-03-18T13:19:37+00:00"

输出结果为:

$ ./manage.py loaddata articles/fixtures/initial_data.json 
Installed 3 object(s) from 1 fixture(s)

请注意,'2013-03-16 17:41:28 UTC+0000' 不是正确的带时区日期时间格式,它会导致以下错误:

DeserializationError: Problem installing fixture 'articles/fixtures/initial_data.json': [u"'2013-03-16 17:41:28 UTC+0000' value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."]

10

如果您正在使用 yaml 进行序列化,那么在 PyYaml 中反序列化 datetime 时可能会出现 bug:

https://code.djangoproject.com/ticket/18867

建议使用 json 作为序列化器,或者您可以在 .yaml 文件中添加引号来包含日期时间。


为时区感知的日期时间添加引号对我没有起作用。使用JSON也不行。 - Daniel
1
在我的yaml文件中,我使用引号更新了日期,如下所示,这解决了我的问题:date_joined: '2016-04-09 13:57:32.123456+00:00' - Lingster

2
你可能需要仔细查看你的 created_at 字段(你知道 auto_now_add=True 吗?)。 我猜测你正在使用什么,因此你可以尝试一些类似的操作。
import datetime
from django.utils.timezone import utc

Article.created_at = datetime.datetime.utcnow().replace(tzinfo=utc)

或者您可以通过设置来禁用时区支持。
USE_TZ = False

在你的settings.py文件中,
或者你可以将不带时区信息的日期时间转化为带时区信息的日期时间。
import datetime
import pytz
utc=pytz.UTC

#  where ever you get your datetime from
unaware = datetime.datetime(2013,3,16,17,41,28,0)

now_aware = utc.localize(unaware)

我通过 ./manage.py loaddata path_to_file 或者 ./manage.py syncdb(只有自动的部分)来加载 fixtures,而不是在 Python 代码中直接进行。这对你的回答有任何影响吗? - ducin
那听起来你的原始数据没有特定的时区 - 所以尝试 USE_TZ = False - danodonovan
3
如果整个项目都启用了时区支持(USE_TZ = True),我认为最好准备有时区意识的测试数据。无论如何,你的提示帮助我找到了准确的答案,所以我给了一个加1的赞,谢谢! - ducin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接