Skip to content Skip to sidebar Skip to footer

What Is An Efficient Way To Do An And/or Search Django-postgres App?

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 pub

Solution 1:

I'm not sure if there is a way to do this. I wanted to say try combining filter with Q but then chanced upon these:

Combining AND OR in Django Queries

and

AND OR in Django queries II

Solution 2:

I think I may have found a solution to my own question. If I have the following tags:

query1 = "men"query2 = "women"query3 = "fashion"query4 = "design"

And I want to find all publications that have men OR women AND fashion OR design tags, it seems to work if I do:

pubs = Publication.objects.filter(Q(tags__title__iexact=query1) | Q(tags__title__iexact=query2) and (Q(tags__title__iexact=query3) | Q(tags__title__iexact=query4)))

After looking at this question: Django query filter combining AND and OR with Q objects don't return the expected results, I changed one of the suggested solutions (which had not been accepted) to use 'and' instead of '&' and it seems to be working although I have no idea why.

Post a Comment for "What Is An Efficient Way To Do An And/or Search Django-postgres App?"