[Django]-Django ArrayAgg – filtering annotated array

7πŸ‘

In order to get length of an ArrayField, you will need to use a different function, there is cardinality and also array_length. More info here https://www.postgresql.org/docs/current/functions-array.html

If you have just one dimenssion array you can use cardinality

from django.db import models

class ArrayLength(models.Func):
    function = 'CARDINALITY'


qs = Publisher.objects.annotate(
    x=ArrayAgg(
        Case(
            When(
                books__language__in=lang_ids,
                then="books__name"
            )
        )
    )
)
qs = qs.annotate(x_len=ArrayLength('x')) # notice `x_len` is just a name, you can use anything
qs = qs.filter(x_len=2)  # the actual filter

πŸ‘€Gabriel Muj

Leave a comment