Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query JSONField for with keys of numerals only

Tags:

python

django

I've taken the following example from Django's documentation, except replaced added a key '99':

>>> Dog.objects.create(name='Rufus', data={
... 'breed': 'labrador',
...     'owner': {
...         'name': 'Bob',
...         'other_pets': [{
...             'name': 'Fishy',
...         }],
...     },
... })
>>> Dog.objects.create(name='Meg', data={'breed': 'collie', '99': 'FINDME',})

>>> Dog.objects.filter(data__breed='collie')
<QuerySet [<Dog: Meg>]>

I want the following to also return the "Meg" Dog:

Dog.objects.filter(data__99='FINDME')

However, it seems that because my key is an integer, Django doesn't handle this properly. How do I have integer keys that are strings in python jsonfields?

like image 825
theicfire Avatar asked May 10 '17 22:05

theicfire


1 Answers

There is a wontfix Django ticket about this.

It is documented behavior:

If the key is an integer, it will be interpreted as an index lookup in an array.

If the key you wish to query by clashes with the name of another lookup, use the jsonfield.contains lookup instead.

So the suggested solution is to use jsonfield.contains:

Dog.objects.filter(data__contains={'99': 'FINDME'})

Anyway I suggest you to avoid numeric keys inside json fields because with the contains approach you cannot perform startswith and other similar lookups (see this similar question) such as Dog.objects.filter(data__99__startswith='FIND').

like image 182
Vanni Totaro Avatar answered Oct 14 '22 15:10

Vanni Totaro