Django Query __isnull=True or = None

纵然是瞬间 提交于 2020-07-31 16:31:29

问题


this is a simple question. I'd like to know if it is the same to write:

queryset = Model.objects.filter(field=None)

than:

queryset = Model.objects.filter(field__isnull=True)

I'm using django 1.8


回答1:


They are equal:

>>> str(Person.objects.filter(age__isnull=True).query) == str(Person.objects.filter(age=None).query)
True
>>> print(Person.objects.filter(age=None).query)
SELECT "person_person"."id", "person_person"."name", "person_person"."yes", "person_person"."age" FROM "person_person" WHERE "person_person"."age" IS NULL
>>> print(Person.objects.filter(age__isnull=True).query)
SELECT "person_person"."id", "person_person"."name", "person_person"."yes", "person_person"."age" FROM "person_person" WHERE "person_person"."age" IS NULL



回答2:


Just to keep in mind that you cannot reverse the condition with your first solution:

# YOU CANNOT DO THIS
queryset = Model.objects.filter(field!=None)

However you can do this:

queryset = Model.objects.filter(field__isnull=False)



回答3:


It depends on the type of field. As mentioned in other answers, they are usually equivalent but in general, this isn't guaranteed.

For example, the Postgres JSON field uses =None to specify that the json has the value null while __isnull=True means there is no json:

https://docs.djangoproject.com/en/3.0/ref/contrib/postgres/fields/#jsonfield



来源:https://stackoverflow.com/questions/29858701/django-query-isnull-true-or-none

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!