Django在关系模型属性的特定值上注释查询集

pyt*_*had 5 python django django-models

假设有这样的结构:

PARTICIPATION_STATUSES = (
    (0, 'No, thanks'),
    (1, 'I may attend'),
    (2, 'I\'ll be there'),
)

class Model1(models.Model):
    # ...

class Model2(models.Model):
    status = models.PositiveIntegerField(
        _('participation status'), choices=PARTICIPATION_STATUSES)    
    field = models.ForeignKey(Model1, related_name='model1_participation')
Run Code Online (Sandbox Code Playgroud)

我想要做的是Model1Model2状态等于特定值的对象计数来注释每个对象(状态号是这个特定的例子).

在我的伪代码中,它看起来像:

queryset = Model1.objects.all()
queryset.annotate(declined=Count('model1_participation__status=0'))
queryset.annotate(not_sure=Count('model1_participation__status=1'))
queryset.annotate(accepted=Count('model1_participation__status=2'))
Run Code Online (Sandbox Code Playgroud)

但是我无法以这种方式注释查询集,因为Django无法解析status=<n>.

什么是实现我想要的正确方法?

小智 6

如果您使用的是Django 1.8或更高版本,则可以使用条件聚合,这些应该适用于查询集annotate.

from django.db.models import IntegerField, Case, When, Count


queryset = Model1.objects.all()

queryset = queryset.annotate(
    declined=Count(
        Case(When(model1_participation__status=0, then=1),
             output_field=IntegerField())
    ),
    not_sure=Count(
        Case(When(model1_participation__status=1, then=1),
             output_field=IntegerField())
    ),
    accepted=Count(
        Case(When(model1_participation__status=2, then=1),
             output_field=IntegerField())
    )
)
Run Code Online (Sandbox Code Playgroud)