I have the following models:
class Company(CachedModel):
name = models.CharField(max_length=255)
class UserExtendedProfile(CachedModel):
company =
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.
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.