[Django]-Group by Foreign Key and show related items โ€“ Django

18๐Ÿ‘

โœ…

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.

๐Ÿ‘คandrefsp

7๐Ÿ‘

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.

๐Ÿ‘คFydo

Leave a comment