考虑一下简单的Django型号Event
和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)
可以很容易地使用参与者总数来注释事件查询:
events = Event.objects.all().annotate(participants=models.Count('participant'))
How to annotate with count of participants filtered by 100?
我需要查询all events,而不考虑参与者的数量,例如,我不需要根据带注释的结果进行筛选.如果有0
个参与者,没关系,我只需要0
个注释值.
example from documentation在这里不起作用,因为它从查询中排除对象,而不是用0
注释它们.
Update. Django 1.8有了新的conditional expressions feature,所以现在我们可以这样做:
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()
)))
Update 2. Django 2.0具有新的Conditional aggregation特性,请参见下面的the accepted answer.
Update 3.美元换Django 3.x,请给我check this answer below美元.