[Django]-Django: Optimal way to select manytomany object with a particular attribute

3👍

That is very inefficient: it gets all related users and iterates through.

A ManyToManyField returns a queryset. So you can use the normal queryset filtering methods, to do all that in a single command:

return self.app.users.filter(user=user_obj).exists()

Note this uses the exists() method to return a bool directly from the database, rather than evaluating the actual objects.

Leave a comment