Django 聚合文档给出了这个示例,该示例计算与每个 Publisher
相关的 Book
的数量,并返回一个查询集,其中前 5 个出版商用他们的图书数量注释(比如用这个计数附加一个新字段):
>>> pubs = Publisher.objects.annotate(num_books=Count('book')).order_by('-num_books')[:5]
>>> pubs[0].num_books
1323
但我只需要计算特定类型的书。类似的东西。
>>> pubs = Publisher.objects.annotate(num_books=Count('book__type="nonfiction"')).order_by('-num_books')[:5]
我是否可以使用过滤器来完成此操作,或者我是否需要求助于原始 SQL?
以上是类似于我的实际问题的文档示例,当系统和医院都被建模为医疗保健实体
时,通过系统中医院的数量来识别和量化最大的医疗组小号:
>>> biggest_systems = Entity.objects.filter(relationships__type_id=NAME_TO_TYPE_ID.get('hospital')).annotate(num_hospitals=Count('relationships')).order_by('-num_hospitals')[:5]
>>> biggest_systems[0].num_hospitals
25
relationships
是带有直通表的实体 M2M 字段,type_id 也是实体内的字段:
class Entity(models.Model):
id = models.AutoField(verbose_name='ID',primary_key=True, db_column='ID')
type_id = models.IntegerField(verbose_name='detailed type',db_column='TypeID', blank=True, editable=True, choices=ENTITYTYPE_CHOICES, help_text="A category for this healthcare entity.")
relationships = models.ManyToManyField('self', verbose_name='affiliated with', through='EntityRelationship', symmetrical=False, related_name='related_to+')
最佳答案
参见 Order of annotate() and filter() clauses :
Publisher.objects.filter(book__rating__gt=3.0).annotate(num_books=Count('book'))
或者在你的情况下:
Publisher.objects.filter(book__type='nonfiction').annotate(num_books=Count('book'))
关于python - 在 Django 中有一种方法可以根据相关对象的条件聚合关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12102843/