Django-用ManytoMany关系计数来注释 [英] Django - Annotate with count across ManytoMany relationships
问题描述
我找不到用多对多关系中的元素使用次数计数来注释查询集的方法。
I am not able to find the way to annotate a queryset with a count of how many times an element is used in a many-to-many relationship.
class Profile(models.Model):
[...]
# Profile can have multiple roles
roles = models.ManyToManyField('Role', blank=True)
[...]
class Role(models.Model):
company = models.ForeignKey(Company, on_delete=models.CASCADE)
name = models.CharField(blank=True, max_length=30)
description = models.CharField(blank=True, max_length=300)
[...]
例如,我将有5个角色:
For example I would have 5 roles:
- Role1
- Role2
- Role3
- Role4
- Role5
- Role1
- Role2
- Role3
- Role4
- Role5
和分配了以下角色的2个配置文件:
And 2 profiles with following roles assigned:
- 个人资料1
- 角色1
- 角色2
- 角色e 1
- 角色3
- 角色4
我想查询角色模型并注释具有该角色的配置文件数量。
I want to query the Role model and annotate with the number of profile that have that role.
因此返回一个查询集,例如
So return a queryset like
Role1: company, name, description, profile_count=2 Role2: company, name, description, profile_count=1
etc ...
我已经尝试过了,但是不起作用:
I have tried that but it does not work:
Role.objects.annotate(profile_count=Count('profile__roles'))
似乎返回
是否知道可以在Django中本地完成还是需要原始SQL请求?
Any idea if that can be done natively in Django or if a raw SQL request is necessary?
谢谢!
推荐答案
如果我正确理解了您,则只需要这样:
If i understand you correctly you just want this:
Role.objects.annotate(profile_count=Count('profile'))
几乎是您所写的。
这篇关于Django-用ManytoMany关系计数来注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!