Django:如何聚合/注释多对多关系?
我有一个 Person 模型和一个 Tag 模型,它们之间有一个 m2m。
我需要提取与给定人员查询集中最多记录相关的标签以及计数。
有没有一种优雅、有效的方法来使用 Django ORM 提取它?
更好的是,有没有办法通过一些注释来获取整个标签分布?如何才能拉出连接到通过 m2m 连接的对象子集的所有对象?
谢谢!
I have a Person model and a Tag model, with a m2m between them.
I need to extract the tag which is connected to the most records within a given Person queryset, together with the count.
Is there an elegant, efficient way to extract this using the Django ORM?
Better yet, is there a way to get the entire tag distribution through some annotation? How can one even pull all of the objects connected to a subset of objects connected via a m2m?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这将为您提供最常见的标签:
This would give you the most frequent tag:
我以前遇到过类似的问题。在我的例子中,m2m 关系是在
Unit
和Weapon
模型之间定义的。我使用以下查询来找出每个Unit
使用的武器数量,并按武器数量的降序对它们进行排序。我会根据您的要求调整查询:
I faced a similar problem before. In my case the m2m relationship was defined between
Unit
andWeapon
models. I used the following query to find out the number of weapons used by eachUnit
and sort them in descending order of number of weapons.I would adjust the query for your requirement thus: