[Answer]-Filtering across two ManyToMany fields

1👍

Django can join across multiple tables at once, so you should be able to do the users query in one step:

events = Event.objects.filter(timestamp__gt=min_time)
users = User.objects.filter(subscribed_orgs__event__in=events).distinct()

(distinct() is necessary since a user could match in multiple ways.)

Since you know the SQL you’re looking for, you can always check the SQL generated by Django to see if it matches your intuition. Check out the Django Debug Toolbar or use connection.queries directly.

Leave a comment