[Answered ]-Table join using the Django ORM

2👍

The trick is to always start from the model you actually want to fetch. In this case, you want to fetch emails, which is a field on the User model. So, start with that model, and use the double-underscore syntax to follow the relationships to Group:

users = User.objects.filter(appuser__group_id=group_id)

In this case, you actually only need a single JOIN, because group_id is a field on AppUser itself (it’s the underlying db field for the group ForeignKey). If you had the group name, you would need two joins:

users = User.objects.filter(appuser__group__name=group_name)

Leave a comment