如何在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
的单个调用,这将确保仅将满足 every 条件的对象排除在外:
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=''))
For more info see this page and this page in the Django docs.
顺便说一句:我的SQL示例只是一个类比-实际生成的SQL代码可能看起来有所不同.通过实际查看它们生成的SQL,您将对Django查询的工作方式有更深入的了解.
这篇关于如何在QuerySet中过滤空或NULL名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!