[Answered ]-Vanilla Django Query to show 'flattened' User/Group (ManyToMany) Listing

1👍

This will get you a list of all users in all groups:

from django.contrib.auth.models import Group

for group in Group.objects.all():
    for user in group.user_set.all():
        print '%s\t%s' % (user.username, group.name)

You can also get the same information in one single query with:

user_groups = Group.objects.values_list('user__username', 'name')

Which will return a list of tuples like so:

[
    ('user1', 'GroupA'),
    ('user1', 'GroupB'),
    ('user2', 'GroupC'),
    ...
]

1👍

For what it’s worth, I also found that:

from django.contrib.auth.models import User, Group

qs =  User.objects.raw("""select *, g.name as groupname
                          from auth_user_groups ug 
                          inner join auth_user u on ug.user_id = u.id
                          inner join auth_group g on ug.group_id = g.id""")
for x in qs:
  print '%s\t%s' % (x.username, x.groupname)

works as desired and returns an actual queryset full of working ‘User’ object references.

It certainly doesn’t satisfy my original question criteria of wanting do do this “somehow using as ‘plain’ of Django magic as possible” though so I’ve accepted solarissmoke’s answer. Figured I’d add my hack here as a potential answer for posterity’s sake anyway though.

Leave a comment