如何在查询集上运行自定义聚合?

时间:2018-01-08 14:11:22

标签: python django django-queryset

我有一个名为LeaveEntry的模型:

class LeaveEntry(models.Model):
    date = models.DateField(auto_now=False, auto_now_add=False)
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.PROTECT,
        limit_choices_to={'is_active': True},
        unique_for_date='date'
    )
    half_day = models.BooleanField(default=False)

我通过过滤器得到一组LeaveEntries:

LeaveEntry.objects.filter(
    leave_request=self.unapproved_leave
).count()

我想获得一个名为总天数的聚合,所以当LeaveEntry有half_day=True时,它就是半天0.5

根据django aggregations docs我的想法是注释这样的日子:

days = LeaveEntry.objects.annotate(days=<If this half_day is True: 0.5 else 1>)

1 个答案:

答案 0 :(得分:3)

你可以使用django的条件表达式Case and When(仅适用于django 1.8 +):

保持the order of filter() and annotate()风,您可以计算未经批准的树叶的剩余天数,如下所示:

from django.db.models import FloatField, Case, When
# ...
LeaveEntry.objects.filter(
    leave_request=self.unapproved_leave  # not sure what self relates to
    ).annotate(
        days=Count(Case(
            When(half_day=True, then=0.5),
            When(half_day=False, then=1),
            output_field=FloatField()
            )
        )
    )