Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django JSONField isnull lookup

As far as I know you can't use __isnull lookups on django native JSONField. On the Internet I found this inactive issue. As possible workaround we can of course use these hacks:

  1. model.objects.filter(field__contains={'key': None}), which isn't so flexible since you might need to query multiple keys or whatever.

  2. model.objects.exclude(field__key=True).exclude(field__key=False), which is hacky and works only for boolean data.

I hope there is a better way ((c) Raymond Hettinger) of doing this. Any advises will be appreciated. For now, I will go with the first approach

like image 656
valignatev Avatar asked Jul 22 '16 14:07

valignatev


1 Answers

According to this (see the last, closing comment) the following should work model.objects.filter(field__key=None) (But obviously you should use the Django version with the fix).

The django docs

warn that

Since any string could be a key in a JSON object, any lookup other than those listed below will be interpreted as a key lookup. No errors are raised. Be extra careful for typing mistakes, and always check your queries work as you intend.

and here they are

like image 69
Bob Avatar answered Sep 21 '22 01:09

Bob