Django无法自动保存DateTimeFields

时间:2012-10-31 19:49:45

标签: django django-models django-admin

嗨我有这样的模特:

from datetime import datetime


class Project(models.Model):
    created = models.DateTimeField(editable=False)
    updated = models.DateTimeField(editable=False)
    product = models.ForeignKey('tool.product')
    module = models.ForeignKey('tool.module')
    model = models.ForeignKey('tool.model')
    zipcode = models.IntegerField(max_length=5)

    def save(self, **kwargs):
        if not self.id:
            self.created = datetime.now()
        self.updated = datetime.now()
        super(Project, self).save()

    def __unicode__(self):
        return self.id

然而,当我尝试保存项目时,我得到了:

coercing to Unicode: need string or buffer, long found

并从runserver:

RuntimeWarning: DateTimeField received a naive datetime (2012-10-31 14:45:36.611622) while time zone support is active.

我不确定这里究竟是什么问题,但我认为这与timezone阻碍DateTimeField的方式有关。

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:4)

首先,DateTimeField支持自动更新,如下所示:

created = models.DateTimeField(editable=False, auto_now_add=True) # Only on creation
updated = models.DateTimeField(editable=False, auto_now=True)     # On every save

其次,你得到的RuntimeWarning意味着你已经启用了 settings.py时区感知日期时间对象,例如,您将看到以下内容:

USE_TZ = True

当你这样做时,你必须以不同的方式对待datetime对象,你必须通过 明确地tzinfo值。

# install the `pytz` module through pip or whatnot
from pytz import timezone
import datetime
from django.utils.timezone import utc

now = datetime.datetime.utcnow().replace(tzinfo=utc)

# To show the time in Greece
athens = timezone('Europe/Athens')
print now.astimezone(athens)

有关详细信息,请参阅django docspytz docs

关于coercing to Unicode:错误,请尝试执行以下操作:

def __unicode__(self):
    return unicode(self.id)

答案 1 :(得分:0)

我在创建时存储now所做的工作是使用DateTimeField的default属性,Django's now() wrapper是这样的:

from django.utils import timezone

ctime = models.DateTimeField(default=timezone.now)

请注意,此日期是UTC时区,如果您需要设置其他时区,请将timezone.now换成调用localtime()的lambda