Django查询:如何从开始和结束时间字段中找到最长持续时间? [英] Django Query : how do I find the maximum time duration from start and end time fields?

查看:1320
本文介绍了Django查询:如何从开始和结束时间字段中找到最长持续时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的Django模型:

Here is my Django model:

class Shift(models.Model):
        worker = models.OneToOneField('Worker',null=True)
        date = models.DateField(null=True)
        shiftTime = models.CharField(max_length=10, default="N/A")
        timeIn = models.TimeField(null=True)
        timeOut = models.TimeField(null=True)

我需要找到一个在给定日期范围内在办公室度过最多时间的工作人员。如何计算Django查询中的timeIn和timeOut字段的持续时间?

I need to find a worker who spent the maximum amount of time in the office in a given date range. How do I calculate the time duration from timeIn and timeOut field in Django query?

编辑:我不想使用其他属性持续时间,因为这似乎是多余的。有没有其他方法可以使用原始查询或持续时间属性?

I don't want to use another attribute duration because that seems redundant. Is there any other way to do it than using raw query or duration attribute?

推荐答案

Django 1.10介绍了通过ORM本机做日期/时间差异。这个查询可以让你得到最长的转移:

Django 1.10 introduced the ability to natively do date/time diffs through the ORM. This query would get you the longest shift:

from django.db.models import DurationField, ExpressionWrapper, F

longest_shift = Shift.objects.annotate(shift_length=ExpressionWrapper(
                                           F('timeOut') - F('timeIn'),
                                           output_field=DurationField()))\.
                                           order_by('-shift_length').first()

您可以添加一个过滤器之前添加 filter()子句所需的特定日期范围。

You can add a filter for a specific date range as required by adding a filter() clause before annotate().

这篇关于Django查询:如何从开始和结束时间字段中找到最长持续时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆