0

I am facing a problem while filtering a record from the database. In my database I have records which contain a dictfield.

for eg region is a dictionary which contains other dictionaries like

region = {'eastus': {'percentage_change': 0}, 'westus': {'percentage_change': 0}}

and I want to fetch eastus or westus.

I have tried something like this, but I am getting an empty list.

MyModel.objects.filter(region__eq='eastus')

any suggestions for this problem?

Vikas Gautam
  • 239
  • 1
  • 4
  • 21

1 Answers1

0

I believe you can achieve this with the exists operator (http://docs.mongoengine.org/guide/querying.html#query-operators)

MyModel.objects.filter(region__eastus__exists=True)

Regarding the OR, you should use the Q class (http://docs.mongoengine.org/guide/querying.html#advanced-queries), thus:

MyModel.objects.filter(Q(region__eastus__exists=True) | Q(region__westus__exists=True))

If you have keys that aren't simple (e.g including fancy character or simply a dash), you can use the __raw__ operator:

MyModel.objects.filter(__raw__={'region.a-fancy-key': {'$exists': True}})

bagerard
  • 5,681
  • 3
  • 24
  • 48