如何过滤查询集中的空名称或 NULL 名称?

发布于 2024-07-20 05:48:04 字数 215 浏览 7 评论 0原文

我有 first_namelast_name 和 我需要搜索的alias(可选)。 因此,我需要一个查询来为我提供所有设置了别名的名称。

除非我能做到:

Name.objects.filter(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.

Only if I could do:

Name.objects.filter(alias!="")

So, what is the equivalent to the above?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

我的鱼塘能养鲲 2024-07-27 05:48:04

您可以这样做:

Name.objects.exclude(alias__isnull=True)

如果您需要排除空值和空字符串,首选方法是将条件链接在一起,如下所示:

Name.objects.exclude(alias__isnull=True).exclude(alias__exact='')

将这些方法链接在一起基本上独立地检查每个条件:在在上面的示例中,我们排除了 alias 为 null 或 空字符串的行,因此您将获得所有具有非空值的 Name 对象,非空alias 字段。 生成的 SQL 看起来像这样:

SELECT * FROM Name WHERE alias IS NOT NULL AND alias != ""

您还可以将多个参数传递给对 exclude 的单个调用,这将确保只有满足 每个 条件的对象才会被排除:

Name.objects.exclude(some_field=True, other_field=True)

这里, some_field other_field 为 true 的行被排除,因此我们得到两个字段都不为 true 的所有行。 生成的 SQL 代码看起来有点像这样:

SELECT * FROM Name WHERE NOT (some_field = TRUE AND other_field = TRUE)

或者,如果您的逻辑比这更复杂,您可以使用 Django 的 Q 对象

from django.db.models import Q
Name.objects.exclude(Q(alias__isnull=True) | Q(alias__exact=''))

有关详细信息,请参阅 此页面此页面 Django 文档。

顺便说一句:我的 SQL 示例只是一个类比——实际生成的 SQL 代码可能看起来会有所不同。 通过实际查看它们生成的 SQL,您将更深入地了解 Django 查询的工作原理。

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 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.

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.

浅笑轻吟梦一曲 2024-07-27 05:48:04
Name.objects.filter(alias__gt='',alias__isnull=False)
Name.objects.filter(alias__gt='',alias__isnull=False)
若相惜即相离 2024-07-27 05:48:04

首先,Django 文档强烈建议不要对基于字符串的字段(例如 CharField 或 TextField)使用 NULL 值。 阅读文档以获取解释:

https://docs.djangoproject。 com/en/stable/ref/models/fields/#null

解决方案:
我认为,您还可以将 QuerySet 上的方法链接在一起。 试试这个:

Name.objects.exclude(alias__isnull=True).exclude(alias="")

这应该会给你你正在寻找的套装。

Firstly, the Django docs strongly recommend not using NULL values for string-based fields such as CharField or TextField. Read the documentation for the explanation:

https://docs.djangoproject.com/en/stable/ref/models/fields/#null

Solution:
You can also chain together methods on QuerySets, I think. Try this:

Name.objects.exclude(alias__isnull=True).exclude(alias="")

That should give you the set you're looking for.

温折酒 2024-07-27 05:48:04

如果要排除 null (None)、空字符串 ("") 以及包含空格的字符串 (" ") ,您可以将 __regex__isnull 过滤选项一起使用

Name.objects.filter(
    alias__isnull = False, 
    alias__regex = r"\S+"
)

alias__isnull=False 排除所有空列

aliax__regex = r"\S+ " 确保列值至少包含一个或多个非空白字符。

If you want to exclude null (None), empty string (""), as well as a string containing white spaces (" "), you can use the __regex along with __isnull filter option

Name.objects.filter(
    alias__isnull = False, 
    alias__regex = r"\S+"
)

alias__isnull=False excludes all the columns null columns

aliax__regex = r"\S+" makes sure that the column value contains at least one or more non whitespace characters.

情深已缘浅 2024-07-27 05:48:04

1. 使用排除时,请记住以下几点以避免常见错误:

不应多个条件添加到 排除中() 块类似于 filter()。 要排除多个条件,您应该使用multiple exclude()

示例:(NOT a AND NOT b)

Entry.objects.exclude(title='').exclude(headline='')

等于

SELECT... WHERE NOT title = '' AND NOT headline = ''

================================== ======================

2. 仅当您真正了解时才使用多个:

示例:NOT (a AND b)

Entry.objects.exclude(title='', headline='')

等于

SELECT.. WHERE NOT (title = '' AND headline = '')

1. When using exclude, keep the following in mind to avoid common mistakes:

Should not add multiple conditions into an exclude() block like filter(). To exclude multiple conditions, you should use multiple exclude().

Example: (NOT a AND NOT b)

Entry.objects.exclude(title='').exclude(headline='')

equal to

SELECT... WHERE NOT title = '' AND NOT headline = ''

======================================================

2. Only use multiple when you really know about it:

Example: NOT (a AND b)

Entry.objects.exclude(title='', headline='')

equal to

SELECT.. WHERE NOT (title = '' AND headline = '')
千寻… 2024-07-27 05:48:04

从 Django 1.8 开始,

from django.db.models.functions import Length

Name.objects.annotate(alias_length=Length('alias')).filter(alias_length__gt=0)

From Django 1.8,

from django.db.models.functions import Length

Name.objects.annotate(alias_length=Length('alias')).filter(alias_length__gt=0)
不顾 2024-07-27 05:48:04

你可以简单地这样做:

Name.objects.exclude(alias="").exclude(alias=None)

真的就是这么简单。 filter 用于匹配,exclude 用于匹配除指定内容之外的所有内容。 这将在 SQL 中计算为 NOT alias='' AND alias IS NOT NULL

You can simply do this:

Name.objects.exclude(alias="").exclude(alias=None)

It's really just that simple. filter is used to match and exclude is to match everything but what it specifies. This would evaluate into SQL as NOT alias='' AND alias IS NOT NULL.

层林尽染 2024-07-27 05:48:04

另一种方法使用通用 isempty 查找,可用于任何字段。

它也可以被 django rest_framework 或其他使用 django 查找的应用程序使用:

from distutils.util import strtobool
from django.db.models import Field
from django.db.models.lookups import BuiltinLookup

@Field.register_lookup
class IsEmpty(BuiltinLookup):
    lookup_name = 'isempty'
    prepare_rhs = False

    def as_sql(self, compiler, connection):
        sql, params = compiler.compile(self.lhs)
        condition = self.rhs if isinstance(self.rhs, bool) else bool(strtobool(self.rhs))
        if condition:
            return "%s IS NULL or %s = ''" % (sql, sql), params
        else:
            return "%s <> ''" % sql, params

然后您可以像这样使用它:

Name.objects.filter(alias__isempty=False)

Another approach using a generic isempty lookup, that can be used with any field.

It can also be used by django rest_framework or other apps that use django lookups:

from distutils.util import strtobool
from django.db.models import Field
from django.db.models.lookups import BuiltinLookup

@Field.register_lookup
class IsEmpty(BuiltinLookup):
    lookup_name = 'isempty'
    prepare_rhs = False

    def as_sql(self, compiler, connection):
        sql, params = compiler.compile(self.lhs)
        condition = self.rhs if isinstance(self.rhs, bool) else bool(strtobool(self.rhs))
        if condition:
            return "%s IS NULL or %s = ''" % (sql, sql), params
        else:
            return "%s <> ''" % sql, params

You can then use it like this:

Name.objects.filter(alias__isempty=False)
一口甜 2024-07-27 05:48:04

这是另一种简单的方法。

Name.objects.exclude(alias=None)

this is another simple way to do it .

Name.objects.exclude(alias=None)
和我恋爱吧 2024-07-27 05:48:04

这个问题已经很老了,但我会尝试一下,因为我在这里没有看到类似的答案,这仍然可能对将来的人有所帮助。

如果您需要过滤 CharField 或 TextField 或任何其他不应在数据库中存储为 Null 的类似 char 的字段,您可以使用 Q() 对象和否定运算符,如下所示:

from django.db.models import Q

not_empty_str_condition = ~Q(alias='')
Name.objects.filter(not_empty_str_condition)

这里否定运算符将执行与我们编写的相反的操作在滤波器、反相操作中。

如果您犯了错误并且在基于文本的字段中设置了 null=True,或者您需要能够为空的基于文本的字段存储 Null,您还可以使用 & 连接这两个条件。 (和)或| (或)运算符。 在这种情况下,您将需要 &,类似的东西:

from django.db.models import Q

not_empty_str_condition = ~Q(alias='') & Q(alist__isnull=False)
Name.objects.filter(not_empty_str_condition)

希望有人会发现这很有用。

This question is quite old, but i will give it a shot since i see no similar answer here and this still might help somebody in future.

If you need to filter CharField or TextField or any other char-like field that should not be stored as Null in the database, you can use Q() object and negating operator, like this:

from django.db.models import Q

not_empty_str_condition = ~Q(alias='')
Name.objects.filter(not_empty_str_condition)

Here negating operator will do opposite of what we write in filter, inverting operation.

In case you've made a mistake and have null=True at your text-based field, or you need to be able to store Null for empty text-based field, you can also join those two conditions using & (and) or | (or) operators. In this case you will need &, something along those lines:

from django.db.models import Q

not_empty_str_condition = ~Q(alias='') & Q(alist__isnull=False)
Name.objects.filter(not_empty_str_condition)

Hope somebody will find this useful.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文