Django 1.11 Annotating a Subquery Aggregate

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

    If I understand correctly, you are trying to count Spaces available in a Carpark. Subquery seems overkill for this, the good old annotate alone should do the trick:

    Carpark.objects.annotate(Count('spaces'))
    

    This will include a spaces__count value in your results.


    OK, I have seen your note...

    I was also able to run your same query with other models I had at hand. The results are the same, so the query in your example seems to be OK (tested with Django 1.11b1):

    activities = Activity.objects.filter(event=OuterRef('pk')).values('event')
    count_activities = activities.annotate(c=Count('*')).values('c')
    Event.objects.annotate(spaces__count=Subquery(count_activities))
    

    Maybe your "simplest real-world example" is too simple... can you share the models or other information?

提交回复
热议问题