djangoormdjango-aggregationdjango-subquery

Sum of Subquery fields django


I have the following subquery:

Subquery(
         ContestTaskRelationship.objects.filter(
             contest=contest,
             solved=OuterRef('id')
         ).values('cost').all()
)

I need then to annotate my QuerySet with sum of cost values returned by each Subquery. How to do that? Wrapping the subquery in Sum returns only the first element of each subquery.


Solution

  • I found a way without Subquery:

    cost_sum=Sum(
                Case(
                    When(
                        contest_task_relationship__contest=contest,
                        then='contest_task_relationship__cost'
                    ),
                    default=V(0),
                    output_field=IntegerField()
                )
            )
    

    Not an elegant way, but it works.