如何在Django中过滤对象的计数注解? [英] How to filter objects for count annotation in Django?
问题描述
考虑简单的Django模型事件
和参与者
:
Consider simple Django models Event
and Participant
:
class Event(models.Model):
title = models.CharField(max_length=100)
class Participant(models.Model):
event = models.ForeignKey(Event, db_index=True)
is_paid = models.BooleanField(default=False, db_index=True)
可以轻松地向参与者总数注释事件查询:
It's easy to annotate events query with total number of participants:
events = Event.objects.all().annotate(participants=models.Count('participant'))
如果用过滤的参与者的注释如何注释is_paid = True
?
How to annotate with count of participants filtered by is_paid=True
?
我需要无论参与者人数如何,查询所有事件我不需要通过注释结果进行过滤。如果有 0
参与者,那没关系,我只需要注释价值 0
I need to query all events regardless of number of participants, e.g. I don't need to filter by annotated result. If there are 0
participants, that's ok, I just need 0
in annotated value.
示例来自文档在这里不起作用,因为它不包括查询中的对象,而不是使用 0
注释它们。
The example from documentation doesn't work here, because it excludes objects from query instead of annotating them with 0
.
更新。 Django 1.8新增了条件表达式功能,所以现在我们可以这样做:
Update. Django 1.8 has new conditional expressions feature, so now we can do like this:
events = Event.objects.all().annotate(paid_participants=models.Sum(
models.Case(
models.When(participant__is_paid=True, then=1),
default=0,
output_field=models.IntegerField()
)))
推荐答案
刚刚发现Django 1.8有新的< a href =https://docs.djangoproject.com/en/1.10 / ref / models / conditional-expressions />条件表达式功能,所以现在我们可以这样做:
Just discovered that Django 1.8 has new conditional expressions feature, so now we can do like this:
events = Event.objects.all().annotate(paid_participants=models.Sum(
models.Case(
models.When(participant__is_paid=True, then=1),
default=0, output_field=models.IntegerField()
)))
这篇关于如何在Django中过滤对象的计数注解?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!