0

如果某个字段为真,我需要计算并存储一年后的日期。但似乎 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)
4

1 回答 1

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)
于 2013-05-22T20:16:52.090 回答