I’m new to Python/Django and i have a question.
I need to get a QuerySet filtered by a Value from a multidimensional dictionary (JSONField).
So far, I got this:
def make_cond(name, value):
from django.utils import simplejson
cond = simplejson.dumps({key:value})[1:-1] # remove '{' and '}'
return ' ' + cond # avoid '"'
Post.objects.filter(JSONField__contains=make_cond('key', 'value'))
That works, but only for the 1st dimension of the dict.
How can I reach the other dimensions?
SQL can’t help you with that.
Given an arbitrary json object whose serialization might look like this,
you’d have to construct a LIKE clause that matches, say, the
{"a", then another{and then"b": "B"without caring what’s in place of"c": "C". A LIKE clause supports wildcards only before and after, so you can’t get what you want.It’s possible you could figure it out with a fulltext index; you could try Haystack or Sphinx for that.
The correct tool for the job, though, is a NoSQL database like mongodb.