2

Suppose I've a JSONField namely "data" defined in one of my models.py in Django. The Contents of the field is somewhat similar to the following -

{
    "name": "John",
    "email": "johndoe@foo.bar",
    "last name": "Doe"
}

I need to write a queries of the following form -

self.objects.filter(data__name="John")

How do I write a similar query for the key "last name". I'm not able to proceed since that key has a space. Was thinking of getting the data and filtering it using python, But I think there would be more efficient way to get it done.

I've not real control over the data in the JSONField. So, I can't really change the name of the key.

deltaforce
  • 524
  • 1
  • 8
  • 25
  • 1
    This might help: https://stackoverflow.com/questions/1227091/how-to-dynamically-provide-lookup-field-name-in-django-query – Harun Yilmaz Jun 03 '20 at 06:48

2 Answers2

6

We can achieve it the following way -

lookup = "data__last name"
self.objects.filter(**{lookup: "Doe"})
deltaforce
  • 524
  • 1
  • 8
  • 25
3

For JSON field you can use contains:

self.objects.filter(data__contains={"last name": "Doe"})
Atul Mishra
  • 1,898
  • 2
  • 13
  • 18