Group by Foreign Key and show related items – Django

Question:

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

Asked By: karthikr

||

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.

Answered By: andrefsp

If you are simply trying to accomplish this for display purposes, take a look at:
https://docs.djangoproject.com/en/1.8/ref/templates/builtins/#regroup

It lets you do just that inside the template.

Answered By: Fydo
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.