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.
This will give you results matching all tags, as your example indicated with
and
. If in fact you neededor
instead, you will probably need Q objects.Edit: I think I have what you're looking for now.
I tested this and it seems to work really well.
Edit 2: Credit to kezabelle in #django on Freenode for the initial idea.
You can use this way:
By this way you can use dynamically generated field names. Also you can use
Q.AND
forAND
condition.Just prepare a tag list first then, query like this: