Filtering in the dictionary list for the jsonfield in Django

65 Views Asked by At

I have a django model that uses json column.

class ClassName(models.Model):
    data = JsonField(default=dict, blank=True, null=True, )

This is the schema in the json field.

{
   "name": "foo",
   "thing":[
      {
        "id": "1",
        "key": "hello"
      },
      {
        "id": "2",
        "key": "world"
      }
   ]
}

Is it possible to search against one key value in the list of dictionaries using ILIKE (icontains) operator? ClassName.objects.filter(data__thing__key__icontains="wo")

Maybe someone has faced this problem? I will be glad of any considerations

ClassName.objects.filter(data__thing__contains=[{'key':'world'}]) - works (but only contains)

ClassName.objects.filter(data__thing__1__key__icontains='wo') - works (but only with the indication of the element)

.raw(""" 
    SELECT DISTINCT id 
    FROM classname, json_array_elements(data::json -> 'thing') as i 
    WHERE i->> 'key' ILIKE '%%{}%%'  """.format('wo')
    ) - works (but only raw)
1

There are 1 best solutions below

0
mahdi hoseyni On

i think you can use __contains lookup to search for a specific key-value pair within a JSONField like this :

search_term = "wo"
query = ClassName.objects.filter(Q(data__thing__contains=[{"key__icontains": search_term}]))

this should work