Search code examples
djangojsonfield

Django jsonfield, is it possible to filter with json array value length?


Suppose I have a jsonfield with data

from django.contrib.postgres.fields import JSONField

class Foo(models.Model):
   json_field = JSONField(default=dict)

json_field = {
  'bar': [1,2,3,4]
}

I'd like to filter data where bar has array length greather than 3

Something like the following, Foo.objects.filter(json_field__bar__length__gt=3)


Solution

  • You can try this:

    Create one more field in the model i.e json_field_bar_length.

    class Foo(models.Model):
        ....
        json_field_bar_length = models.IntegerField(default=0)
    

    And enter the length of json_field['bar'] into it whenever you save the json_field in it and check if the length is greater or not.