在查询集中过滤空或NULL名称 [英] Filtering for empty or NULL names in a queryset
问题描述
只有我能做到:
Name.objects.filter(alias!=)
那么等于上面的那个?
你可以这么做:
Name.objects.exclude(alias__isnull = True)
如果您需要排除空字符串和空字符串,首选的方法是将条件链接在一起:
Name.objects.exclude(alias__isnull = True).exclude(alias__exact ='')
将这些方法链接在一起基本上独立地检查每个条件:在上面的例子中,我们排除了别名
的行是null 或一个空字符串,所以您得到所有名称
对象具有非空,不为空的别名
字段。生成的SQL将如下所示:
SELECT * FROM Name WHERE别名IS NOT NULL AND alias!=
您还可以将多个参数传递给单个调用 exclude
,这将确保只有满足每个条件的对象被排除:
Name.objects。排除(some_field = True,other_field = True)
这里, some_field
和 other_field
是真的被排除,所以我们得到两个字段不是真的所有行。生成的SQL代码看起来有点像这样:
SELECT * FROM Name WHERE NOT(some_field = TRUE AND other_field = TRUE)
或者,如果你的逻辑比这更复杂,你可以做这样的事情,虽然我只推荐它作为最后的手段:
从django.db.models导入Q
Name.objects.exclude(Q (alias__isnull = True)| Q(alias__exact =''))
我的SQL示例只是一个类比 - 实际生成的SQL代码可能看起来不同。您将通过实际查看生成的SQL来更深入地了解Django查询的工作原理。
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.
Only if I could do:
Name.objects.filter(alias!="")
So, what is the equivalent to the above?
You could do this:
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='')
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 != ""
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)
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)
Alternatively, if your logic is more complex than that, you could do something like this, although I only recommend it as a last resort:
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.
As an aside: My SQL examples are just an analogy--the actual generated SQL code will probably look different. You'll get a deeper understanding of how Django queries work by actually looking at the SQL they generate.
这篇关于在查询集中过滤空或NULL名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!