8

I need to query a model by a JsonField, I want to get all records that have empty value ([]):

I used MyModel.objects.filter(myjsonfield=[]) but it's not working, it returns 0 result though there's records having myjsonfield=[]

0m3r
  • 12,286
  • 15
  • 35
  • 71
mou55
  • 660
  • 1
  • 8
  • 13

4 Answers4

5

Use the dunder __exact for this. The __isnull=True does not work because the JSONField is technically not null.

MyModel entries where myjsonfield is empty:

MyModel.objects.include(myjsonfield__exact=[])

MyModel entries where myjsonfield is not empty:

MyModel.objects.exclude(myjsonfield__exact=[])

https://docs.djangoproject.com/en/3.1/ref/models/querysets/#std:fieldlookup-exact

I believe if you've set the default=dict in your model then you should use {} (eg: myjsonfield__exact={}) instead of [] but I haven't tested this.

TheZeke
  • 706
  • 7
  • 16
1
  1. Firstly, Django actually recommends that you declare JSONField with immutable/callable default values. For your example:

     class MyModel(models.Model):
         myjsonfield = models.JSONField(null=True, default=list)
    
  2. Secondly, to query by null JSONField:

     MyModel.objects.filter(myjsonfield__isnull=True)
    

    To query for fields having default value ([] in your case):

     MyModel.objects.filter(myjsonfield__exact=[])
    

See https://docs.djangoproject.com/en/4.0/topics/db/queries/#querying-jsonfield for more details and examples.

0

JSONfield should be default={} i.e., a dictionary, not a list.

e.barojas
  • 252
  • 3
  • 11
  • 1
    No it shouldn't. JSON can be a list or a dict at root level. In Django having it as default={} doesn't return in order of entry. Having it as a list allows some order to it. – James Bellaby Dec 28 '20 at 13:18
  • 1
    It can be either. `default=dict` or `default=list` since JSON can be either a dict or a list. Don't set it to actual value of {} or [] and don't actually call the function (eg. `dict()`) though. Set it to the name of the function that produces the value. It will be called when it needs to set a default. – TheZeke Mar 04 '21 at 22:21
-1

Try MyModel.objects.filter(myjsonfield='[]').

zxzak
  • 8,985
  • 4
  • 27
  • 25