mou55
mou55

Reputation: 730

Query by empty JsonField in django

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=[]

Upvotes: 10

Views: 5309

Answers (4)

Ankit Kumar Singh
Ankit Kumar Singh

Reputation: 71

  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.

Upvotes: 1

TheZeke
TheZeke

Reputation: 816

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.

Upvotes: 7

e.barojas
e.barojas

Reputation: 302

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

Upvotes: 0

zxzak
zxzak

Reputation: 9446

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

Upvotes: -1

Related Questions