Django 1.11 Annotating a Subquery Aggregate

后端 未结 6 866
醉酒成梦
醉酒成梦 2020-11-28 04:22

This is a bleeding-edge feature that I\'m currently skewered upon and quickly bleeding out. I want to annotate a subquery-aggregate onto an existing queryset. Doing this bef

6条回答
  •  余生分开走
    2020-11-28 04:39

    It's also possible to create a subclass of Subquery, that changes the SQL it outputs. For instance, you can use:

    class SQCount(Subquery):
        template = "(SELECT count(*) FROM (%(subquery)s) _count)"
        output_field = models.IntegerField()
    

    You then use this as you would the original Subquery class:

    spaces = Space.objects.filter(carpark=OuterRef('pk')).values('pk')
    Carpark.objects.annotate(space_count=SQCount(spaces))
    

    You can use this trick (at least in postgres) with a range of aggregating functions: I often use it to build up an array of values, or sum them.

提交回复
热议问题