django使用q对象动态过滤 [英] django dynamically filtering with q objects
问题描述
我试图根据用户输入标签查询数据库。标签的数量可以是0-5,所以我需要动态创建查询。
所以我有一个标签列表,tag_list,我想查询数据库:
design_list = Design.objects.filter(Q(tags__tag__contains =tag1)和Q(tags__tag__contains =tag2 )等等)
如何创建此功能?
你需要循环使用tag_list并为每个应用一个过滤器。
tag_list = ['tag1','tag2','tag3']
base_qs = Design.objects.all()
for t in tag_list:
base_qs = base_qs.filter(tags__tag__contains = t)
这将为您提供与 / em>标签,您的示例以和
表示。如果事实上你需要或
,你可能需要Q对象。
编辑: strong>我想我现在有你想要的东西。
tags = ['tag1','tag2',' tag3']
q_objects = Q()#在标签中创建一个空的Q对象,以
开头:
q_objects | = Q(tags__tag__contains = t)#'或'Q对象一起
designs = Design.objects.filter(q_objects)
我测试
编辑2:在Freenode的#django中感谢kezabelle的初步想法。 >
I'm trying to query a database based on user input tags. The number of tags can be from 0-5, so I need to create the query dynamically.
So I have a tag list, tag_list, and I want to query the database:
design_list = Design.objects.filter(Q(tags__tag__contains = "tag1") and Q(tags__tag__contains = "tag2") and etc. etc. )
How can I create this feature?
You'll want to loop through the tag_list and apply a filter for each one.
tag_list = ['tag1', 'tag2', 'tag3']
base_qs = Design.objects.all()
for t in tag_list:
base_qs = base_qs.filter(tags__tag__contains=t)
This will give you results matching all tags, as your example indicated with and
. If in fact you needed or
instead, you will probably need Q objects.
Edit: I think I have what you're looking for now.
tags = ['tag1', 'tag2', 'tag3']
q_objects = Q() # Create an empty Q object to start with
for t in tags:
q_objects |= Q(tags__tag__contains=t) # 'or' the Q objects together
designs = Design.objects.filter(q_objects)
I tested this and it seems to work really well.
Edit 2: Credit to kezabelle in #django on Freenode for the initial idea.
这篇关于django使用q对象动态过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!