django dynamically filtering with q objects

人走茶凉 提交于 2019-11-27 05:28:08

问题


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?


回答1:


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.




回答2:


You can use this way:

my_dict = {'field_1': 1, 'field_2': 2, 'field_3': 3, ...}  # Your dict with fields
or_condition = Q()
for key, value in my_dict.items():
    or_condition.add(Q(**{key: value}), Q.OR)

query_set = MyModel.objects.filter(or_condition)

By this way you can use dynamically generated field names. Also you can use Q.AND for AND condition.




回答3:


Just prepare a tag list first then, query like this:

tags = ['tag1', 'tag2',...]
design_list = Design.objects.filter(tags__tag__contains__in = tags)


来源:https://stackoverflow.com/questions/13076822/django-dynamically-filtering-with-q-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!