Django datetime不能按预期工作

时间:2013-05-22 20:12:50

标签: django django-models django-views

如果某个字段为True,我需要计算并存储未来一年的日期。但似乎datetime不能像我期望的那样工作。 date字段已正确填充,但featured_to_date字段在任何情况下都始终为空。这是模型:

import datetime
from datetime import timedelta

class Site(models.Model):
    ...
    date = models.DateTimeField()
    featured = models.BooleanField(default=False)
    featured_to_date = models.DateTimeField(blank=True,null=True)
    ...

    def save(self, *args, **kwargs):
        if not self.id:
            self.date = datetime.datetime.now()
        if self.featured:
            oneyear = timedelta(days=365)
            featured_to_date = datetime.datetime.now() + oneyear
        super(Site, self).save(*args, **kwargs)

1 个答案:

答案 0 :(得分:4)

您需要设置self.featured_to_date,而不是featured_to_date,如下所示:

def save(self, *args, **kwargs):
    if not self.id:
        self.date = datetime.datetime.now()
    if self.featured:
        oneyear = timedelta(days=365)
        self.featured_to_date = datetime.datetime.now() + oneyear
    super(Site, self).save(*args, **kwargs)