hob*_*obs 5 python sql django django-queryset
Django汇总文档给出了以下示例,该示例计算Book与每个相关的s 的数量,Publisher并返回一个查询集,该查询集的前5名出版商均标有其图书计数(例如,在此字段中添加新的计数):
>>> pubs = Publisher.objects.annotate(num_books=Count('book')).order_by('-num_books')[:5]
>>> pubs[0].num_books
1323
Run Code Online (Sandbox Code Playgroud)
但是我只需要数一本特定类型的书。就像是。
>>> pubs = Publisher.objects.annotate(num_books=Count('book__type="nonfiction"')).order_by('-num_books')[:5]
Run Code Online (Sandbox Code Playgroud)
是否可以使用过滤器来完成此操作,还是需要使用原始SQL?
上面是与我的实际问题类似的docs示例,即当系统和医院都被建模为医疗机构时,通过其系统中医院的数量来识别和量化最大的医疗组Entity:
>>> 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
Run Code Online (Sandbox Code Playgroud)
relationships 是具有穿透表的Entity M2M字段,type_id也是Entity中的字段:
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+')
Run Code Online (Sandbox Code Playgroud)
请参阅annotate() 和 filter() 子句的顺序:
Publisher.objects.filter(book__rating__gt=3.0).annotate(num_books=Count('book'))
Run Code Online (Sandbox Code Playgroud)
或者在你的情况下:
Publisher.objects.filter(book__type='nonfiction').annotate(num_books=Count('book'))
Run Code Online (Sandbox Code Playgroud)