[Answered ]-Django query to Sum the lengths of ArrayFields

2👍

It turns out that the custom aggregate function is the way to go!

With the following:

from django.db.models import Aggregate

class SumCardinality(Aggregate):
    template = 'SUM(CARDINALITY(%(expressions)s))'

The query is as simple as:

Interaction.objects().filter(xxx).\
    values('user_id').annotate(codes_len=SumCardinality('codes'))
👤TAH

Leave a comment