姜戈:分组依据?
我正在寻找类似以下内容的内容:
previous_invoices = Invoice.objects.filter(is_open=False)
.order_by('-created')
.group_by('user')
但是 group_by()
不存在...
这将为每个用户找到最近关闭的发票。
这个 聚合 API 似乎可以让你做这样的事情来计数和总和,但我不需要计数或总和或任何东西,我实际上想要发票对象!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
选项 1:
虽然 Django 中不存在
group_by()
,但您可以尝试利用latest()
方法和过滤器用户也是如此:对于旧版本的 Django,
latest()
不存在,查询将如下所示:选项 2:
更新:从那时起我就这样做了此处添加了问答样式示例: 如何在 Django ORM 中执行 GROUP BY ... COUNT 或 SUM?,展示如何在 Django ORM 上模拟
GROUP BY
操作。< /em>如果您绝对想创建
group_by
的效果,那么您可以手动创建一个,如此处接受的答案所示:Django GROUP BY 字段值。注意:
存在这个库django-group-by 声称在 Django 上添加了
group_by()
,您可能需要检查一下。Option 1:
Although a
group_by()
does not exist in Django, you can try and work around on retrieving the most recently closed invoice for each user by utilizinglatest()
method and filter for a user as well:For older versions of Django were
latest()
does not exist, the query will look like this:Option 2:
UPDATE: I have since then added a Q&A style example here: How to execute a GROUP BY ... COUNT or SUM in Django ORM? that shows how to simulate a
GROUP BY
operation on Django ORM.If you absolutely want to create the effects of a
group_by
, then you can create one manually as shown in the accepted answer here: Django GROUP BY field value.Note:
There exists this library django-group-by which claims to add a
group_by()
on Django you may want to check.此页面来自 2007 年谁将其破解到了 django,但这毫无意义,因为 1.1 之前的版本确实有一个未记录的 group_by`。但一年前的这条帖子似乎有一些见解。本质上:
另请参阅使用
extra
的提及,以及可能失败的神奇方式。祝你好运。There's this page from 2007 who hacked it to django, but that would be moot since pre 1.1 does have an undocumented group_by` anyway. But this thread from a year ago seems to have some insights. Essentially:
See also the mentions of using
extra
, and also the magical ways in which that can fail. Best of luck.