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

时间:2013-05-03 09:03:46

标签: django django-models django-queryset isnull

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

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?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:5)

我更喜欢处理得更好的第二种解决方案

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

查询集可以处理Null值。基于此User.objects.filter(username=None),这将仅获取username = NULL的值