用平均日期差注释查询集吗? (django) [英] Annotate a queryset with the average date difference? (django)

查看:91
本文介绍了用平均日期差注释查询集吗? (django)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我到处搜索了答案,但是找不到任何东西。也许这只是一个愚蠢的问题,还是一个非常棘手的问题。这里是:

I searched all over place for an answer to this but couldn't find anything. Perhaps this is just a stupid question or a really tricky one. Here it is:

让我们说我的模型是这个(伪django代码):

Let's say my model is this (pseudo django code):

Event
  type = ForeignKey(EventType)
  name = CharField
  date_start = DateField
  date_end = DateField

EventType
  name = CharField

我想知道的是每种事件类型的平均持续时间。我现在要做的是计算每次创建新事件时的平均持续时间(保存方法),并将其存储在EventType的average_duration列中。这种方法的问题在于,我无法回答诸如 Y年期间 类型的X事件的平均持续时间是多少之类的问题。因此,与其添加更多列来回答诸如此类的问题,我不希望它是实时完成的。

What I want to know is the average duration time for each event type. What I do now is calculate the average duration whenever a new event is created (save method) and have that stored in an average_duration column in EventType. The problem with this approach is that I cannot answer questions like "what was the average duration time for events of type X, during the year Y". So instead of adding more columns to answer questions like these I would prefer to have it done in "real-time".

这可以通过注释查询集来完成吗?首先,我必须获取每种事件类型的日期差,然后得出它们的平均值,然后用该平均值注释事件查询集。

Can this be done by annotating the queryset? First I would have to get the date differences for each event type, then come up with their average, and then annotate the Event queryset with that average, I assume.

推荐答案

只是一个更新。在Django> = 1.8中,可以执行以下操作:

Just an update. In Django >= 1.8 it is possible to do:

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

duration = ExpressionWrapper(F('date_end') - F('date_start'), output_field=fields.DurationField())

events_with_duration = Event.objects.annotate(duration=duration)

之后,您可以运行以下查询:

after which you can run queries like:

events_with_duration.filter(duration__gt=timedelta(days=10))

这篇关于用平均日期差注释查询集吗? (django)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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