125
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.
41
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.
- [Django]-Python/Django: how to assert that unit test result contains a certain string?
- [Django]-Access request in django custom template tags
- [Django]-Numeric for loop in Django templates
3
Just prepare a tag list first then, query like this:
tags = ['tag1', 'tag2',...]
design_list = Design.objects.filter(tags__tag__contains__in = tags)
- [Django]-(13: Permission denied) while connecting to upstream:[nginx]
- [Django]-Add Text on Image using PIL
- [Django]-What is the difference between {% load staticfiles %} and {% load static %}
2
You may need to add AND and OR conditions
query = (Q(fild1='ENABLE'))
# Filter by list
query.add(Q(fild2__in=[p.code for p in Objects.field.all()]), Q.AND)
# filter OR
q_objects = Q(field3='9999999')
for x in myList:
q_objects.add(Q(field3=x.code), Q.OR)
query.add(q_objects, Q.AND)
- [Django]-How do I import the Django DoesNotExist exception?
- [Django]-What is the best approach to change primary keys in an existing Django app?
- [Django]-Django Rest Framework β Could not resolve URL for hyperlinked relationship using view name "user-detail"
1
Use reduce :
from functools import reduce
design_list = Design.objects.filter(reduce(lambda q1,q2: q1 & q2,
[Q(tags__tag__contains=t)
for t in tag_list]))
- [Django]-Difference between User.objects.create_user() vs User.objects.create() vs User().save() in django
- [Django]-Get user information in django templates
- [Django]-Need to convert a string to int in a django template
Source:stackexchange.com