[英]TypeError: unsupported operand type(s) for +: 'DateField' and 'datetime.timedelta'
In my model there are start_date_time
, end_date_time
, period
and period_type
fields, where end_date_time
must be equal to sum of start_date_time
and timedelta.在我的 model 中有
start_date_time
、 end_date_time
、 period
和period_type
字段,其中end_date_time
必须等于start_date_time
和 timedelta 的总和。 And in my case timedelta's day is equal to period
and period_type
is one of days/months/years/.在我的情况下,timedelta 的天等于
period
,而period_type
是天/月/年/之一。 Here are my codes:这是我的代码:
models.py
: models.py
:
class PeriodTypeEnum(models.IntegerChoices):
Years = 'years'
Months = 'months'
Days = 'days'
class Policy(models.Model):
policy_type = models.ForeignKey('PolicyType', on_delete=models.CASCADE)
blank = models.OneToOneField('blank_app.Blank', on_delete=models.CASCADE)
period = models.IntegerField()
period_type = models.IntegerField(choices=PeriodTypeEnum.choices)
start_date_time = models.DateField(blank=True, null=True)
end_date_time = models.DateField(default = start_date_time + timedelta(days=1), blank=True, null=True)
PS: in end_date_time
field, timedelta(days + x) - x must be equal to period
. PS:在
end_date_time
字段中, timedelta(days + x) - x 必须等于period
。
Django doesn't support dependencies like that in default
. Django 不支持
default
中的依赖项。
The easiest thing to do here is to declare这里最简单的做法是声明
end_date_time = models.DateField(blank=True, null=True)
and add a并添加一个
def clean(self):
if not self.end_date_time:
# (or do something with `self.period`?)
self.end_date_time = self.start_date_time + timedelta(days=1)
to the model.到 model。 Remember that
.clean()
is only called by forms and such, not when you .save()
, so if you want that, you'll need to override .save()
too.请记住, .clean
.clean()
仅由 forms 等调用,而不是在您调用.save()
时,因此如果需要,您也需要覆盖.save()
。
def save(self, **kwargs):
self.clean()
return super().save(**kwargs)
This code will not work, because start_date_time
is not a value, but a field that will keep a value.此代码将不起作用,因为
start_date_time
不是一个值,而是一个将保留值的字段。
As was mentioned in previous answer, you can override clean/save methods to set value for end_date_time
.正如前面的答案中提到的,您可以覆盖 clean/save 方法来设置
end_date_time
的值。 Another option is to use pre_save or post_save signals depending on when/how start_date_time
is set.另一种选择是根据
start_date_time
的设置时间/方式来使用pre_save或post_save信号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.