其他分享
首页 > 其他分享> > Django:分组依据?

Django:分组依据?

作者:互联网

我正在寻找类似以下内容的东西:

previous_invoices = Invoice.objects.filter(is_open=False)
                                   .order_by('-created')
                                   .group_by('user')

但是group_by()不存在…

这将为每个用户找到最近关闭的发票.

这个aggregation API似乎可以让您对计数和总和进行类似的操作,但是我不需要计数或总和之类的东西,我实际上想要发票对象!

解决方法:

选项1:

尽管Django中不存在group_by(),但您可以尝试通过利用latest()方法和用户过滤器来为每个用户检索最近关闭的发票:

previous_invoices = Invoice.objects.filter(user=my_user, is_open=False)
                                   .latest('created') 

对于较旧的Django版本,则不存在Latest(),查询将如下所示:

previous_invoices = Invoice.objects.filter(user=my_user, is_open=False)
                                   .order_by('-created')[0]

选项2:

如果您绝对要创建group_by的效果,则可以手动创建一个,如此处接受的答案所示:Django GROUP BY field value.

  1. Use 07002 with flat=True to get a list of the existent values in your database (if you don’t know them beforehand). Also use .distinct() to elimintae duplicate values as we do not care for those:

    06002

  2. Now iterate through value_list and fill your dictionary:

    06003

Now group_by_value dictionary contains as keys the distinct values
in your interesting_field and as values the queryset objects, each
containing the entries of MyModel with interesting_field=a value
from value_list
.

注意:

该库django-group-by存在,它声称要在Django上添加您可能要检查的group_by().

标签:django-orm,python,django,group-by
来源: https://codeday.me/bug/20191210/2099950.html