Python列表按位运算
有没有办法获取 django 查询表达式列表(例如 Q(first_name="Jordan")
,其中 Q
是 django.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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可能希望
这将在
search_params
中的所有项目之间放置按位或 (|
),以空条件Q()
开始。You probably want
This will place a bit-wise or (
|
) between all the items insearch_params
, starting with an empty conditionQ()
.