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?
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With