计算Django模型中两个datefield的差异



我在Django模型中有两个datefields字段,start_dateend_date。我想计算并存储两者之间的总天数,这将与每日费用一起使用,以返回总成本。

models.py

class Booking(models.Model):
"""Stores the bookings, for example when it was made, the booking date, and the car ID."""
# Unique ID for this booking.
start_date = models.DateField(default=timezone.now)
end_date = models.DateField(null=True)

大多数答案建议提取天数函数(使用start_date.day),但这不起作用。如果预订开始于11月30日,结束于12月2日,则该函数将返回28天,因为它单独减去了整数。

使用简单的加减法:

duration = end_date - start_date 

返回错误:

TypeError: 'DateField' and 'DateField'不支持的操作数类型

我已经尝试使用嵌套在模型中的函数,它从end_date减去每天,直到它达到start_date:

def get_total_days(self):
"""Computes total number of days car will be rented from with a basic While loop."""
# Create separate instances of start and end day so as not to tamper with db values.
start_day = self.start_date
end_day = self.end_date
days = 0
while end_day > start_day:
days += 1
end_day -= 1
return days

但是这会引发错误:

异常值:不支持的操作数类型-=:'datetime '。日期'和'int'

你能帮忙吗?

添加一个方法或属性来减去实例的日期:

@property
def duration(self):
return (self.end_date - self.start_date).days