Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 587
mou55 Avatar asked Nov 10 '22 09:11

mou55


1 Answers

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.

like image 111
TheZeke Avatar answered Nov 14 '22 21:11

TheZeke