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 such a company:

 Company A User 1 User 2 Company B User 3 user 4 

I tried a few things and the closest I could get:

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

However, it just gives me results something like this:

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

Any inputs?

thanks

+7
source share
2 answers

You can add multiple arguments to your order_by() method. Therefore, you can order inside orders.

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

For a structure such as:

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

Try using 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 the user structure you want.

+7
source

If you are just trying to do this for show, take a look: https://docs.djangoproject.com/en/1.8/ref/templates/builtins/#regroup

It allows you to do this only inside the template.

+3
source

All Articles