I would like to filter a queryset by whether a certain subquery returns any results. In SQL this might look like this:
SELECT * FROM events e WHERE EXISTS
(SELECT * FROM tags t WHERE t.event_id = e.id AND t.text IN ("abc", "def"))
In other words, retrieve all events which are tagged with one of the specified tags.
How might I express this using Django’s QuerySet API on models Event and Tag?
You can do something like this:
Assuming that there is a
ForeignKeyfromTagtoEvent.Explanation: You are filtering
Eventobjects based on a specific criteria. Using the double underscore syntax you are accessing thetextattribute of theTaginstances and then attaching theINcondition. 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: