Django:如何聚合/注释多对多关系? [英] Django: how to aggregate / annotate over a many-to-many relationship?

查看:242
本文介绍了Django:如何聚合/注释多对多关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Person模型和一个Tag模型,它们之间有一个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.

有没有一个优雅,有效的方法来使用Django ORM解压缩?

Is there an elegant, efficient way to extract this using the Django ORM?

更好的是,是不是通过一些注释获得整个标签分发的方式?如何才能将连接到通过m2m连接的对象子集的所有对象拉出?

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?

谢谢!

推荐答案

这将给你最常见的标签:

This would give you the most frequent tag:

from django.db.models import Count
Tag.objects.filter(person__yourcriterahere=whatever [, morecriteria]).annotate(cnt=Count('person')).order_by('-cnt')[0]

这篇关于Django:如何聚合/注释多对多关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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