Django:通过'field__isnull = True'或'field = None'过滤查询集? [英] Django: filtering queryset by 'field__isnull=True' or 'field=None'?

查看:302
本文介绍了Django:通过'field__isnull = True'或'field = None'过滤查询集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须用一个动态值(可以是None)来过滤查询集:我可以简单地写:

I have to filter a queryset by a dynamic value (which can be None): may I simply write:

filtered_queryset = queryset.filter(field=value)

还是我应该检查None:

or shall I check for None:

if value is None:
    filtered_queryset = queryset.filter(field__isnull=True)
else:
    filtered_queryset = queryset.filter(field=value)

该行为是否取决于特定的DBMS?

Does the behaviour depend on the particular DBMS?

推荐答案

ORM将为您处理 None (将其投射为NULL)并返回 QuerySet 对象,因此除非您需要捕获 None 输入,否则第一个示例很好。

The ORM will handle None (cast it to NULL) for you and return a QuerySet object, so unless you need to catch None input the first example is fine.

>>> User.objects.filter(username=None)
[]
>>> type(_)
<class 'django.db.models.query.QuerySet'>
>>> str(User.objects.filter(username=None).query)
SELECT "auth_user"."id", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."password", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."is_superuser", "auth_user"."last_login", "auth_user"."date_joined" FROM "auth_user" WHERE "auth_user"."username" IS NULL

这篇关于Django:通过'field__isnull = True'或'field = None'过滤查询集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆