在我的Django项目中,我有一个这样的模型-
class Task(models.Model):
ticket_number = models.CharField()
order_number = models.CharField()
number_of_errors = models.IntegerField()
start_time = models.DateTimeField()
end_time = models.DateTimeField()
我想创建一个查询集"tasks"其中包括working_date、ticket_number、order_number和work_hours(end_time-start_time),格式为HH:MM:SS,例如03:55:01格式。"working_date"将从end_time派生。设置好查询后,我将以CSV格式导出结果。
我可以在MySQL中这样做查询:
SELECT
DATE(end_time) AS working_date,
ticket_number, order_number, TIME_FORMAT((TIMEDIFF(end_time,start_time)),'%H:%i:%s') AS work_hours
FROM
task
WHERE
end_time>= pStartDate AND end_time< pEndDate;
如何在Django ORM中做到这一点?
你可以试试这个
from django.db.models import ExpressionWrapper, F, fields
duration = ExpressionWrapper(F('end_time') - F('start_time'), output_field=fields.DurationField())
task_list = Task.objects.all().annotate(duration=duration)
那么,假设您循环遍历任务并想要找到持续时间
for task in task_list:
print(task.duration)