Django QuerySet首先在组中 [英] Django QuerySet First in Group
问题描述
我有一个查询集,看起来像:
{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 theid
with the earliestdate
. 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 anddistinct()
.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 thedistinct()
operation.这篇关于Django QuerySet首先在组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!