Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group by Foreign Key and show related items - Django

I have the following models:

class Company(CachedModel):
    name = models.CharField(max_length=255)

class UserExtendedProfile(CachedModel):

    company = models.ForeignKey(Company)
    user = models.ForeignKey(User)

I basically need to get a list of users ordered by company like this:

Company A
    User 1
    User 2

Company B
    User 3 
    user 4

I tried a few things, and the closest I could get to is:

users = UserExtendedProfile.objects.values('company', 'user').order_by('company')

However this would just give me results something like this:

[{'company': 1L, 'user': 17L}, {'company': 1L, 'user': 6L}, {'company': 2L, 'user': 15L}]

Any inputs?

Thanks

like image 282
karthikr Avatar asked Oct 04 '12 16:10

karthikr


1 Answers

You can add multiple arguments on your order_by() method. Therefore you can do ordering inside orderings.

users = UserExtendedProfile.objects.values('company', 'user').order_by('company', 'user')

For a structure like:

[{ company: [user1, user2, ] }, ]

Try using a defaultdict

from collections import defaultdict 
users = defaultdict(list)
for result in UserExtendedProfile.objects.values('company', 'user').order_by('company', 'user'):
    users[result['company']].append(result['user'])

With this you should get on users the structure you want.

like image 140
andrefsp Avatar answered Sep 22 '22 09:09

andrefsp