用平均日期差异注释查询集? (姜戈)
我到处寻找这个问题的答案,但找不到任何东西。也许这只是一个愚蠢的问题,或者是一个非常棘手的问题。这里是:
假设我的模型是这样的(伪 django 代码):
Event
type = ForeignKey(EventType)
name = CharField
date_start = DateField
date_end = DateField
EventType
name = CharField
我想知道的是每种事件类型的平均持续时间。我现在要做的是计算创建新事件时的平均持续时间(保存方法)并将其存储在 EventType 的average_duration 列中。这种方法的问题是我无法回答诸如“Y 年期间 X 类型事件的平均持续时间是多少”之类的问题。因此,我宁愿“实时”完成,而不是添加更多列来回答此类问题。
这可以通过注释查询集来完成吗?首先,我必须获取每种事件类型的日期差异,然后得出它们的平均值,然后用该平均值注释事件查询集,我假设。
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:
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
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
只是一个更新。在 Django >= 1.8 中可以执行以下操作:
之后您可以运行如下查询:
Just an update. In Django >= 1.8 it is possible to do:
after which you can run queries like:
您需要使用 额外方法将日期差异添加到每行
然后使用 aggregate 方法来计算刚刚添加的列的平均值:
不过要小心,这该方法速度慢且无法扩展。将计算值存储在 event_type 上是最好的选择。
You'll need to create a queryset with the extra method to add the date difference to each row
Then use the aggregate method to compute the average for your just added column:
Be careful though, this method is slow and won't scale. Storing the computed value on event_type is imho your best option.
我认为最好的选择是使用
date_end - date_start
列创建一个 SQL 视图,在此视图上创建一个 django 模型,然后您将能够查询该视图并根据需要对其进行注释。我已经用与您类似的模型完成了此操作,如果您需要,也许我可以为您提取一些有趣的代码。I think your best bet is to create an SQL view with the
date_end - date_start
column, create a django model on this view and then you will be able to query the view and annotate it as you want. I've done this with models similars to yours and maybe I could extract some interesting code for you if you need.