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?
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')
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With