gpt4 book ai didi

How can I make the queryset filter `or` conditions dynamically from the array?(如何使查询集从数组动态过滤`或`条件?)

转载 作者:bug小助手 更新时间:2023-10-25 17:43:30 25 4
gpt4 key购买 nike



I have array and try to use this as filter key for database

我有数组,并尝试将其用作数据库的筛选键


I want to make this dynamically from the array = [AC" ,"BC"]

我想从数组=[AC“,”BC“]动态地实现这一点


 queryset = queryset.filter(Q(username__icontains="AC")| Q(username__icontains="BC"))

For example, I try like this below but it is obviously wrong.

例如,我试着在下面这样做,但显然是错误的。


array = ["AC","BC"]
qs = []
for k in array:
qs.append(Q(username__icontains=k))

queryset = queryset.filter(qs.join('|'))

How can I do this ?

我怎么能这样做呢?


更多回答
优秀答案推荐

With Q Django's class you might use |= operator to build your query dynamically with OR logic

在Q Django的类中,您可以使用|=运算符通过OR逻辑动态构建查询


query = Q()

for el in array:
query |= Q(username__icontains=el)


you can use reduce to achieve such a thing, like:

您可以使用RECLUTE来实现这样的功能,例如:


from functools import reduce
from operator import or_
final_condition = reduce(or_, conditions_list) # this will be your condition

更多回答

It works for my purpose thank you .

对我来说很管用,谢谢。

I tried this but still reduce is a bit too difficult for me... but thank you very much! I ned to learn more

我试过了,但减体重对我来说还是太难了……但是非常感谢你!我需要了解更多

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com