Search code examples
djangopython-3.xhstore

Query Django's HStoreField values using LIKE


I have a model with some HStoreField attributes and I can't seem to use Django's ORM HStoreField to query those values using LIKE.

When doing Model.objects.filter(hstoreattr__values__contains=['text']), the queryset only contains rows in which hstoreattr has any value that matches text exactly.

What I'm looking for is a way to search by, say, te instead of text and those same rows be returned as well. I'm aware this is possible in a raw PostgreSQL query but I'm looking for a solution that uses Django ORM.


Solution

  • If you want to check value of particular key in every object if it contains 'te', you can do:

    Model.objects.filter(hstoreattr__your_key__icontains='te')
    

    If you want to check if any key in your hstore field contains 'te', you will need to create your own lookup in django, because by default django won't do such thing. Refer to custom lookups in django docs for more info.