Django conditional Subquery aggregate

后端 未结 2 724
夕颜
夕颜 2021-02-20 14:07

An simplified example of my model structure would be

class Corporation(models.Model):
    ...

class Division(models.Model):
    corporation = models.ForeignKey(         


        
2条回答
  •  萌比男神i
    2021-02-20 14:50

    You should be able to do this with a Case() expression to query the count of departments that have the type you are looking for:

    from django.db.models import Case, IntegerField, Sum, When, Value
    
    Corporation.objects.annotate(
        type_10_count=Sum(
            Case(
                When(division__department__type=10, then=Value(1)),
                default=Value(0),
                output_field=IntegerField()
            )
        )
    )
    

提交回复
热议问题