Python列表按位运算

发布于 2024-12-27 16:31:29 字数 853 浏览 3 评论 0原文

有没有办法获取 django 查询表达式列表(例如 Q(first_name="Jordan"),其中 Qdjango.db.models.Q)并将它们按位或在一起?

换句话说,我有这样的事情:

search_string = "various search terms"

我想这样做:

search_params = [Q(description__icontains=term) for term in re.split(r'\W', search_string)]
search_params = something_magical(search_params)
results = Record.objects.filter(search_params)

其中 search_params 现在相当于 Q(description__icontains="various") | Q(description__icontains="search" | Q(description__icontains="terms"

我知道这样的函数是可能的:

def something_magical(lst):
    result = lst[0]
    for l in lst[1:]
        result |= l
    return result

所以我想知道这个功能是否已经内置到Python中了(我假设它比我这里的功能更优化)

虽然我对此应用程序感兴趣,但我也只是在理论上感兴趣。

Is there a way to take a list of django query expresses (e.g. Q(first_name="Jordan"), where Q is django.db.models.Q) and bitwise OR them together?

In other words, I have something like this:

search_string = "various search terms"

And I want to do this:

search_params = [Q(description__icontains=term) for term in re.split(r'\W', search_string)]
search_params = something_magical(search_params)
results = Record.objects.filter(search_params)

where search_params now is equivalent to Q(description__icontains="various") | Q(description__icontains="search" | Q(description__icontains="terms"

I know it would be possible with a function like this:

def something_magical(lst):
    result = lst[0]
    for l in lst[1:]
        result |= l
    return result

So I'm wondering if this functionality is already built into Python (and I'm assuming it's more optimized than my function here).

Although I'm interested in it for this application, I'm also just interested in it theoretically.

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

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

发布评论

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

评论(1

羁〃客ぐ 2025-01-03 16:31:29

您可能希望

import operator 
from functools import reduce    # Python 3
search_params = reduce(operator.or_, search_params, Q())

这将在 search_params 中的所有项目之间放置按位或 (|),以空条件 Q() 开始。

You probably want

import operator 
from functools import reduce    # Python 3
search_params = reduce(operator.or_, search_params, Q())

This will place a bit-wise or (|) between all the items in search_params, starting with an empty condition Q().

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