Don*_*Don 24 django isnull django-models django-queryset
我必须通过动态值(可以是None)过滤查询集:我可以简单地写:
filtered_queryset = queryset.filter(field=value)
Run Code Online (Sandbox Code Playgroud)
或者我应该检查无:
if value is None:
filtered_queryset = queryset.filter(field__isnull=True)
else:
filtered_queryset = queryset.filter(field=value)
Run Code Online (Sandbox Code Playgroud)
行为是否取决于特定的DBMS?
Hed*_*ide 30
ORM将为您处理None
(将其强制转换为NULL)并返回一个QuerySet
对象,因此除非您需要捕获None
输入,否则第一个示例就可以了.
>>> 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
Run Code Online (Sandbox Code Playgroud)
我更喜欢处理得更好的第二种解决方案
Update
if value is None:
filtered_queryset = queryset.filter(field__isnull=True)
//Do some proessing with filtered_queryset object with None values
else:
filtered_queryset = queryset.filter(field=value)
//Do some proessing with filtered_queryset object with not NULL values
Run Code Online (Sandbox Code Playgroud)
查询集可以处理Null值.基于此, User.objects.filter(username=None)
这将仅获取username = NULL的值
归档时间: |
|
查看次数: |
29282 次 |
最近记录: |