[Fixed]-Django: Accessing Many to Many object through another Many to Many relationship

17👍

Well, yes. current_document.teams.all() is a queryset – more or less, a list – of Teams. It doesn’t make sense to ask for current_document.teams.all().users, as a queryset doesn’t itself have a ‘users’ attribute, hence the error. users is an attribute of each Team element within that queryset. So, one way of doing it would be to iterate through the queryset and ask for the users associated with each team.

However, that would be hopelessly inefficient – one database call for each team. A much better way is to ask the database directly: give me all the users who are in teams associated with the current document. Like this:

User.objects.filter(team__documents=current_document)

Leave a comment