In my Django app I have a Publication model and a Tag model which have a many to many relationship.
Let's say I have four tags: men, women, fashion, design. I want to find all publications that have a men OR women tag associated with it, AND a fashion OR design tag associated with it. For example, in a search field I might enter: (men || women) && (fashion || design). In other words, the results should yield publications that have at least one tag from each 'or' pair.
I have figured out how to do just an 'or' search (i.e. find all publications with a tag of men or women or fashion or design) and I have figured out how to do just an and search (i.e. find all publications that have all the tags, men and women and fashion and design), but I do not know the most efficient way to do the and-or combo.
Thus far I have split up the query string to get a list of 'or' pairs, and I started to create a search predicate, but then I thought, what will I do with these results? For example...
if 'qTag' in request.GET:
or_queries = request.GET['qTag'].split('&&')
for or_query in or_queries:
or_query_set = or_query.split()
for sub_query in or_query_set:
if pub_predicate:
pub_predicate = pub_predicate | Q(tags__title__istartswith=sub_query)
else:
pub_predicate = Q(tags__title__istartswith=sub_query)
pubs_for_set = Publication.objects.filter(pub_predicate).distinct()
pubs_for_tags.append(pubs_for_set)
pub_predicate = None
pubs_for_set = None
Doing the above gives me a list (pubs_for_tags) of lists (pubs_for_set) that gives all results for each "or"pair." But now what? I don't know how to proceed with an and search. Can anyone suggest a way to do this?