Annotate a queryset with the average date difference? (django)

こ雲淡風輕ζ 提交于 2019-12-03 11:24:05
ryuusenshi

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))

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!