Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get len of the ArrayField Postgres Django

I've a model:-

class ModelA(models.Model):
    field1 = ArrayField(models.IntegerField())

I want to get the top10 objects of ModelA having maximum length of field1. I see that a len filter is available in Django Docs, but that just does not serves my purpose.

How can I get top10 objects having maximum length of field1?

like image 753
PythonEnthusiast Avatar asked Dec 21 '25 03:12

PythonEnthusiast


1 Answers

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')
like image 173
Ian Price Avatar answered Dec 23 '25 15:12

Ian Price