5

I have Sentence model which metadata as JSONField
One sample row is

Sentence.objects.filter(id=6753315).values('id', 'metadata')[0]

{'id': 6753315,
 'metadata': [{'filters': [{'id': None, 'level_name': 'Brand Hierarchy'},
                           {'id': None, 'level_name': 'Category Hierarchy'}],
               'product': None,
               'themes': [{'id': 35299, 'sentiment': 'Positive'},
                          {'id': 35301, 'sentiment': 'Positive'}]}]}

metadata is list of object and that object have nested list of objects.
I want to query such rows based on theme id. In this example row length of metadata list is 1 and length of themes list is 1 so its easy to query like

In [30]: Sentence.objects.filter(id=6753315, metadata__0__themes__0__contains={"id": 35299})
Out[30]: <QuerySet [<Sentence: Sentence object>]>

But length of metadata and themes can be anything so how can I query such rows to check if some theme id is present in that row or not for any length of metadata and themes.

I just want to find out all the rows which have some particular theme id

Sentence.objects.filter(metadata__*__themes__*__contains={"id": 35299})  

I dont know the index so wrote * to make my problem easy to understand.

Alok
  • 7,734
  • 8
  • 55
  • 100

1 Answers1

0

Wow, I figured it out

Sentence.objects.filter(metadata__contains=[{'themes': [{"id": 35299}]}])