0

Here is what I have.

class Array(Subquery):
    template = 'ARRAY(%(subquery)s)'

class A(models.Model):
    ...

class B(models.Model):
    a = models.ForeignKey(A)

class C(models.Model):
    b = models.ForeignKey(B)

b_sub = B.objects.filter(a=OuterRef('pk').annotate(items=Count('c').values('items')

result = a.objects.annotate(items=Array(b_sub))

And I'm getting

# >>> result.first().items
[4, 6, 10]

But I need the sum of all items(4+6+10)->20 for each A row.

Like this

# >>> result.first().items
20

Is it possible?

3 Answers 3

2

Not sure, understand correct or no your question but what about sql query, like this:

SELECT ID, (SELECT SUM(A) FROM UNNEST(MY_COLUMN) AS A) AS TOTAL FROM MY_TABLE;
Sign up to request clarification or add additional context in comments.

Comments

0

Something like this:

from django.db.models import Sum
result = a.objects.annotate(items=Array(b_sub)).aggregate(Sum(items))

1 Comment

ProgrammingError: function sum(bigint[]) does not exist LINE 1: SELECT SUM("items") FROM (SELECT "A"."id" AS Col1, ARRA... ^ HINT: No function matches the given name and argument types. You might need to add explicit type casts.
0

Following is used for solution

class SubqueryCount(Subquery):
    template = '(SELECT count(*) FROM (%(subquery)s) _count)'
    output_field = IntegerField()


sub = C.objects.filter(b__a=OuterRef('pk')).only('pk')
result = a.objects.annotate(count=SubqueryCount(sub))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.