我正试图在Djago中获得两个Datetiemfield的区别。我尝试覆盖默认的save(),但仍然出现错误。
models.py
class Sample(models.Model):
ad_start = models.DateTimeField()
ad_end = models.DateTimeField()
ad_duration = models.IntegerField()
@property
def get_time_diff(self):
timediff = self.ad_end - self.ad_start
return timediff
#return relativedelta(self.ad_end, self.ad_start)
def save(self, *args, **kwargs):
self.ad_duration = self.get_time_diff()
super(Sample, self).save(*args, **kwargs)
forms.py
class SampleForm(forms.ModelForm):
class Meta:
model = Sample
exclude = ("submitted", 'ad_duration', "list_date" )
widgets = {
'ad_start': DatePickerInput(),
'ad_end': DatePickerInput(),
}
错误
Django Version: 2.1.7
Exception Type: TypeError
Exception Value:'datetime.timedelta' object is not callable
答案 0 :(得分:2)
您的代码需要进行两项更改。
首先,您需要从方法@property
中删除get_time_diff
。因为您无法通过()
调用属性方法。或者,您仍然可以保留property方法,但不要在save函数中调用它,例如:self.ad_duration = self.get_time_diff
第二,您需要将模型字段更新为DurationField,以存储在get_time_diff
中创建的时间增量对象。像这样:
class Sample(models.Model):
ad_start = models.DateTimeField()
ad_end = models.DateTimeField()
ad_duration = models.DurationField()
def get_time_diff(self):
timediff = self.ad_end - self.ad_start
return timediff
def save(self, *args, **kwargs):
self.ad_duration = self.get_time_diff()
super(Sample, self).save(*args, **kwargs)
或者您可以从get_time_diff
获取总秒数并将其存储在ad_duration
字段(将是浮点字段)中。
class Sample(models.Model):
ad_start = models.DateTimeField()
ad_end = models.DateTimeField()
ad_duration = models.FloatField()
def get_time_diff(self):
timediff = self.ad_end - self.ad_start
return timediff.total_seconds() # returns value in seconds