我在 Django 模型中有兩個 datefields 欄位,start_date和end_date。我想計算并存盤兩者之間的總天數,這將與每日費用一起使用以回傳總成本。
模型.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' 和 '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”
你能幫忙嗎?
uj5u.com熱心網友回復:
添加減去實體日??期的方法或屬性:
@property
def duration(self):
return (self.end_date - self.start_date).days
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/537300.html
下一篇:TypeError:'>='在'builtin_function_or_method'和'datetime.time'的實體之間不支持
