Django QuerySet首先在组中 [英] Django QuerySet First in Group

查看:290
本文介绍了Django QuerySet首先在组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个查询集,看起来像:

  {id,group_id,date} 

对于由 group_id 键入的每个组,我想返回 id 与最早的日期。我如何在django查询中这样做?或者是更有效的order_by日期,然后使用python dict来忽略第一个相同group_id的所有元素?

解决方案

Django并没有真正拥有 GROUP BY 运算符。您可以尝试通过订购和 distinct()来模拟它。



尝试这样的东西:

  queryset.order_by('group_id','date')。distinct('group_id')
注意: group_id 必须先在订单中执行<$ c $($)

c> distinct()操作。


I have a queryset that looks like:

{id, group_id, date}

For each group, keyed by the group_id, I'd like to return the id with the earliest date. How would I do that in a django query? Or is it more efficient to order_by date and then use a python dict to ignore all elements with the same group_id after the first?

解决方案

Django doesn't really have the GROUP BY operator. You could try to mimic it with ordering and distinct().

Try something like this:

queryset.order_by('group_id', 'date').distinct('group_id')

Note: that the group_id has to be first in the ordering to perform the distinct() operation.

这篇关于Django QuerySet首先在组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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