3
class Language(models.Model):
    iso_code = models.CharField()

class Publisher(models.Model)
    name = models.CharField()

class Book(modle.Model):
    name = models.CharField()
    language = models.ForeignKey(Language)
    publisher = models.ForeignKey(Publisher, related_name='books')

lang_ids = [1,2]

qs = Publisher.objects.annotate(
    x=ArrayAgg(
        Case(
            When(
                books__language__in=lang_ids,
                then="books__name"
            )
        )
    )
)

I want to filter the qs as shown here - https://docs.djangoproject.com/en/3.1/ref/contrib/postgres/fields/#len

qs.filter(x__len=2)

Why is it impossible to filter the qs this way? I am getting an error IndexError: tuple index out of range.

Output field in ArrayAgg is ArrayField

class ArrayAgg(OrderableAggMixin, Aggregate):
    function = 'ARRAY_AGG'
    template = '%(function)s(%(distinct)s%(expressions)s %(ordering)s)'
    allow_distinct = True

    @property
    def output_field(self):
        return ArrayField(self.source_expressions[0].output_field)

    def convert_value(self, value, expression, connection):
        if not value:
            return []
        return value
sheesh
  • 51
  • 1
  • 6

1 Answers1

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
  • 3,682
  • 1
  • 19
  • 28