[Django]-Get len of the ArrayField Postgres Django

0๐Ÿ‘

โœ…

I was finally able to get the frequency of the elements in the array as well:-

q = """
with norm (id, element) as (
    select id, unnest(field1) from model;
)
select id, sum(case when element = 2 then 1 else 0 end)  as count
from norm
group by id
order by count
limit 10;
"""


a = Model.objects.raw(q)
๐Ÿ‘คPraful Bagai

4๐Ÿ‘

If you are sure your array is 1-dimensional, you can use PostgreSQL function cardinality

ModelA.objects.extra(select={'length':'cardinality(field1)'}).order_by('length')

Or, using array_length function (with second argument being the number of dimensions sought)

ModelA.objects.extra(select={'length':'array_length(field1,1)'}).order_by('length')
๐Ÿ‘คIan Price

Leave a comment