Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query Django JSONFields that are a list of dictionaries

Given a Django JSONField that is structured as a list of dictionaries:

# JSONField "materials" on MyModel:
[
    {"some_id": 123, "someprop": "foo"},
    {"some_id": 456, "someprop": "bar"},
    {"some_id": 789, "someprop": "baz"},
]

and given a list of values to look for:

myids = [123, 789]

I want to query for all MyModel instances that have a matching some_id anywhere in those lists of dictionaries. I can do this to search in dictionaries one at a time:

# Search inside the third dictionary in each list:
MyModel.objects.filter(materials__2__some_id__in=myids)

But I can't seem to construct a query to search in all dictionaries at once. Is this possible?

like image 381
shacker Avatar asked Nov 16 '25 11:11

shacker


1 Answers

contains might help you. Should be something like this:

q_keys = Q()

for _id in myids:
    q_keys |= Q(materials__contains={'some_id': _id})

MyModel.objects.filter(q_keys)
like image 181
Davit Tovmasyan Avatar answered Nov 19 '25 09:11

Davit Tovmasyan