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
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With