gpt4 book ai didi

django - 使用具有用户动态的 Q 对象进行过滤?

转载 作者:行者123 更新时间:2023-12-03 06:12:52 26 4
gpt4 key购买 nike

在我的views.py中我有一个方法:

#......
def get_filter_result(self, customer_type, tag_selected):
list_customer_filter=[]
customers_filter = Customer.objects.filter(Q(type__name=customer_type),
Q(active=True),
Q(tag__id=tag_selected))

for customer_filter in customers_filter:
customer_filter.list_authorize_sale_type = sale_type_selected(customer_filter.authorize_sale_type)
list_customer_filter.append(customer_filter)
return list_customer_filter

**我的案例 tag_selected 是用户选中的复选框值我对从我的网址传递的 tag_selected(列表=1,2,3,...)有问题

/?customer_type=TDO&tag=2 ===>filter okay
/?customer_type=TDO&tag=3 ===>filter okay
?customer_type=TDO&tag=2,3 ===>How Can I add And condition in filter?

例如

if len(tag_selected)==1:
customers_filter = Customer.objects.filter(Q(type__name=customer_type),
Q(active=True),
Q(tag__id=tag_selected))
else:
customers_filter = Customer.objects.filter(Q(type__name=customer_type),
Q(active=True),
Q(tag__id=tag_selected[0])
Q(tag__id=tag_selected[1])
Q(tag__id=tag_selected[2])
...
)

最佳答案

这适用于单个和多个条件:

idseq = request.POST['tag'].split(',')
tag_qs = reduce(operator.or_, (Q(tag__id=x) for x in idseq))
Customers.objects.filter(..., tag_qs)

关于django - 使用具有用户动态的 Q 对象进行过滤?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1957240/

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