Reputation: 614
I have values in 'codes' JSONField structured like this:
[{"x": "723"}, {"x": "614"}]
I need to get Events objects where event.codes "x" key is IN a list of values, for example ['723', '332', ..]
EDIT
The model is:
from django.contrib.postgres.fields import JSONField
class Events(models.Model):
codes = JSONField(null=False, blank=True, default={})
Upvotes: 7
Views: 11568
Reputation: 1786
Since you want to search inside a list stored in JSONField, you need to use the syntax filter(codes__contains=[{"key": value}]). Note the [] used here.
So for your question we get:
from django.db.models import Q
qs = Events.objects.filter(Q(codes__contains=['723']) | Q(codes__contains=['332']))
If you need to cover more cases, you can chain more Q() calls to this statement.
Upvotes: 0
Reputation: 637
Events.objects.filter(codes__0__x__in=['723','332'])
UPD: From django docs:
If the key is an integer, it will be interpreted as an index lookup in an array
You store list
object in codes
json attribute, so you can lookup it by index (in your case it's zero index).
Upvotes: 6