gpt4 book ai didi

Django:按 'field__isnull=True' 或 'field=None' 过滤查询集?

转载 作者:行者123 更新时间:2023-12-03 10:56:49 25 4
gpt4 key购买 nike

我必须通过动态值(可以是无)过滤查询集:我可以简单地写:

filtered_queryset = queryset.filter(field=value)

或者我应该检查无:
if value is None:
filtered_queryset = queryset.filter(field__isnull=True)
else:
filtered_queryset = queryset.filter(field=value)

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

最佳答案

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

关于Django:按 'field__isnull=True' 或 'field=None' 过滤查询集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16355169/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com