2

If I have, for example:

from django.contrib.postgres.fields import JSONField class MyModel(models.Model): data = JSONField() 

GIVEN a model instance obj1, where data == ['apple', 'banana', 'orange']

GIVEN a model instance obj2, where data == ['banana', 'orange']

GIVEN a model instance obj3, where data == ['apple']

How can I write an ORM query that returns all model instances whose data includes at least one item from a given list, ['apple', 'strawberry']? It should return obj1 and obj3 because both of those objects include 'apple', despite the argument including 'strawberry', which is not represented in any of the objects.

1
  • Don't use a JSONFIeld... Commented Jun 11 at 18:06

1 Answer 1

1

You can probably use __has_any_keys [Django-doc]:

MyModel.objects.filter(data__has_any_keys=['apple', 'strawberry'])

But in a relational database where the structure of the data is fixed, you should not treat JSON blobs as non-atomic values [django-antipatterns]. Disclosure: I am the author of that page.

Sign up to request clarification or add additional context in comments.

4 Comments

__has_any_keys seems to operate on the keys though. I'm looking for something that operates on just a basic list of strings. data is a list, like ['apple', 'banana', 'orange'], and not a dictionary like {'apple': 1, 'banana': 2, 'orange': 3}
: that's what I first though too, but the documentation also shows it for an array: postgresql.org/docs/9.5/functions-json.html (well for ?& but it is the same concept).
You're right. This works. Thanks
: I opened a Django ticket to include it in the documentation.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.