如果某个字段为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)
答案 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)