Django 1.11 Annotating a Subquery Aggregate

后端 未结 6 848
醉酒成梦
醉酒成梦 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:55

    Shazaam! Per my edits, an additional column was being output from my subquery. This was to facilitate ordering (which just isn't required in a COUNT).

    I just needed to remove the prescribed meta-order from the model. You can do this by just adding an empty .order_by() to the subquery. In my code terms that meant:

    spaces = Space.objects.filter(carpark=OuterRef('pk')).order_by().values('carpark')
    count_spaces = spaces.annotate(c=Count('*')).values('c')
    Carpark.objects.annotate(space_count=Subquery(count_spaces))
    

    And that works. Superbly. So annoying.

提交回复
热议问题