我正在尝试在django的保存模型中执行基本日期计算,请参阅下面的代码:
class Purchase(models.Model):
purchase_date = models.DateField()
purchase_place = models.CharField(verbose_name='Place of Purchase', max_length=255)
purchaseCategory = models.ForeignKey(PurchaseCategory, verbose_name='Purchase Category')
cost = models.DecimalField(max_digits=11, decimal_places=2)
warranty_period_number = models.IntegerField()
warranty_period_type = models.CharField(max_length=255, choices=(('m', 'Month(s)'), ('y', 'Year(s)')))
warranty_end_date = models.DateField(editable=False)
scan = models.CharField(max_length=255)
alerts = models.BooleanField(verbose_name='Receive Email Alerts?')
user = models.ForeignKey('auth.User', editable=False)
created = models.DateTimeField(editable=False, auto_now_add=True)
modified = models.DateTimeField(editable=False, auto_now=True)
#custom save model
def save(self, *args, **kwargs):
#figure out warranty end date
if self.warranty_period_type == 'm':
self.warranty_end_date = self.purchase_date + self.purchase_date.timedelta(months=self.warranty_period_number)
else:
self.warranty_end_date = self.purchase_date + self.purchase_date.timedelta(years=self.warranty_period_number)
super(Purchase, self).save()
我认为以下内容可行,但没有运气..它的错误:
'datetime.date' object has no attribute 'timedelta'
有人能指出正确的方向去做我想做的事吗?
干杯, 本
答案 0 :(得分:15)
timedelta不接受年限,所以
from datetime import timedelta
# custom save model
def save(self, *args, **kwargs):
# figure out warranty end date
if self.warranty_period_type == 'm':
self.warranty_end_date = self.purchase_date + timedelta(days=self.warranty_period_number*31)
else:
self.warranty_end_date = self.purchase_date + timedelta(days=self.warranty_period_number*365.2425)
super(Purchase, self).save(*args, **kwargs)