[Solved]-Joining ManyToMany fields with prefetch_related in Django


It isn’t possible to access r.areas__name for a Role r. You still have to access the roles via r.areas.all(). However, by using prefetch_related, you fetch all the related objects in one extra query, instead of O(n) queries.

Since you want to order by area name, you should probably use the Area model for your queryset, then loop through the related roles.

areas = Area.objects.filter(id__in=[1, 2, 3]).order_by('name').prefetch_related('role_set')

for area in areas:
    roles = area.role_set.all()
    for role in roles:
        print area.name, roles.name

That should give you the ordering you want, as long as the Role model is ordered by name by default. If not, you could use a Prefetch object to order the related queryset.

Leave a comment