How to "filter" by "exists" in Django? How to "filter" by "exists" in Django? django django

How to "filter" by "exists" in Django?


You can do something like this:

q = Event.objects.filter(tag__text__in = ['abc', 'def'])

Assuming that there is a ForeignKey from Tag to Event.

Explanation: You are filtering Event objects based on a specific criteria. Using the double underscore syntax you are accessing the text attribute of the Tag instances and then attaching the IN condition. You don't have to worry about the join on foreign key; Django does that for you behind the scenes. In case you are curious to see the query generated, you can print it:

print q.query


Manoj's solution may cause a problem when there are multiple tags for an event.

The SQL inner join returns all the rows so events may have duplicate results, the solution is to add the distinct method.

q = Event.objects.filter(tag__text__in = ['abc', 'def']).distinct()