简体   繁体   中英

Django "LIKE" query for JSONField

I have created model like this:

class Customer(models.Model):
   name = models.CharField(max_length=200)
   data = JSONField()

and data filed has this structure:

Customer.objects.create(name='David', data={
    fields: [
        {id: 1, value: "abc"},
        {id: 2, value: "efg}
    ]
})

If we filter objects with exact data.fields.item, we can do like this:

Customer.obejcts.filter(data__fields__contains=[{id: 1, value: "abc"}])

If we want to filter objects with data.fields.item but with not exact data.fields.item.value as follows, how can we do this? Thanks very much!

Customer.obejcts.filter(data__fields__contains=[{id: 1, value: "b"}])

For raw sql in PostgreSQL, maybe we can do as follows:

SELECT id, json_string(fields,'value') FROM table_name
    WHERE json_string(fields,'value') LIKE '%b%';

And try the following django statement, but it doesn't work:

queryset = Customer.objects\
                .annotate(fieldValue=KeyTextTransform('value', 'fields'))\
                .filter(fieldValue__contains='b')

Emm, I try a raw sql solution with json_array_elements and it works.

def search_like(field):
    return Customer.objects.raw("""
        SELECT *
        FROM customer t, json_array_elements(t.fields::json) AS elem 
        WHERE elem->>'id' = '{}' AND elem->>'value' LIKE '%%{}%%'
    """.format(field['id'], field['value']))

search({'id': 1,'value': 'b'})

Does anyone have better solution without raw sql?

try to use

Customer.objects.filter(data__fields__value__regex ="b", data__fields__id= 1)

for case insensitive use iregex

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM