在Django模型中有两个datefield,即start_date和end_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)大多数答案都建议提取days函数(使用start_date.day),但这是行不通的。如果预订从11月30日开始,到12月2日结束,则函数将返回28天,因为它仅减去整数。
使用简单的加减:
duration = end_date - start_date 返回一个错误:
TypeError:-:“DateField”和“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.date‘和'int’不支持的操作数类型
你能帮个忙吗?
发布于 2022-11-18 13:54:05
添加减去实例日期的方法或属性
@property
def duration(self):
return (self.end_date - self.start_date).dayshttps://stackoverflow.com/questions/74490355
复制相似问题