slumtrimpet slumtrimpet - 1 year ago 77
Python Question

Vanilla Django Query to show 'flattened' User/Group (ManyToMany) Listing

I'm trying to write a simple Django query to show all users in all groups within the vanilla django.contrib.auth models:

User.username |
------------- | -----------
user1 | groupA
user1 | groupB
user2 | groupA
user2 | groupC
user3 | groupA

I'd like to do this somehow using as 'plain' of Django magic as possible here because the goal is to fit this report into an already existing reporting framework that doesn't readily support custom queries and whatnot.

So I'd like to just do something along the lines of:

from django.contrib.auth import UserGroup

for x in UserGroup.objects.all():
print '%s\t%s' % (x.user.username,

... if that ManyToMany table tying User and Group objects were accessible through standard Django model import.

Answer Source

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,

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'),
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download