如何过滤 QuerySet 中的空名称或 NULL 名称? [英] How to filter empty or NULL names in a QuerySet?
问题描述
我有 first_name
, last_name
&我需要搜索的 alias
(可选).所以,我需要一个查询来给我所有设置了别名的名字.
I have first_name
, last_name
& alias
(optional) which I need to search for. So, I need a query to give me all the names that have an alias set.
如果我能做到:
Name.objects.filter(alias!="")
那么,上面的等价物是什么?
So, what is the equivalent to the above?
推荐答案
你可以这样做:
Name.objects.exclude(alias__isnull=True)
如果您需要排除空值和空字符串,最好的方法是将条件链接在一起,如下所示:
If you need to exclude null values and empty strings, the preferred way to do so is to chain together the conditions like so:
Name.objects.exclude(alias__isnull=True).exclude(alias__exact='')
将这些方法链接在一起基本上独立检查每个条件:在上面的示例中,我们排除了 alias
为 null 或 为空字符串的行,因此您将获得所有 Name
具有非空、非空 alias
字段的对象.生成的 SQL 看起来像:
Chaining these methods together basically checks each condition independently: in the above example, we exclude rows where alias
is either null or an empty string, so you get all Name
objects that have a not-null, not-empty alias
field. The generated SQL would look something like:
SELECT * FROM Name WHERE alias IS NOT NULL AND alias != ""
您还可以将多个参数传递给对 exclude
的单个调用,这将确保只有满足所有条件的对象才会被排除:
You can also pass multiple arguments to a single call to exclude
, which would ensure that only objects that meet every condition get excluded:
Name.objects.exclude(some_field=True, other_field=True)
这里,some_field
和 other_field
为真的行被排除,因此我们得到两个字段都不为真的所有行.生成的 SQL 代码看起来有点像这样:
Here, rows in which some_field
and other_field
are true get excluded, so we get all rows where both fields are not true. The generated SQL code would look a little like this:
SELECT * FROM Name WHERE NOT (some_field = TRUE AND other_field = TRUE)
或者,如果您的逻辑比这更复杂,您可以使用 Django 的 Q 对象:
Alternatively, if your logic is more complex than that, you could use Django's Q objects:
from django.db.models import Q
Name.objects.exclude(Q(alias__isnull=True) | Q(alias__exact=''))
有关更多信息,请参阅此页面和此页面 在 Django 文档中.
For more info see this page and this page in the Django docs.
顺便说一句:我的 SQL 示例只是一个类比——实际生成的 SQL 代码可能看起来不同.通过实际查看它们生成的 SQL,您将更深入地了解 Django 查询的工作原理.
这篇关于如何过滤 QuerySet 中的空名称或 NULL 名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!