Adopted from this question on stackoverflow
// models.py
class Company(CachedModel):
name = models.CharField(max_length=255)
class UserExtendedProfile(CachedModel):
company = models.ForeignKey(Company)
user = models.ForeignKey(User)
If you want to order serialized data like below:
Company A
User 1
User 2
Company B
User 3
user 4
Try using a defaultdict
Additionally, multiple arguments can be added to order_by()
method.
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'])
Adopted from this question in stackoverflow.
"to be able to sort objects by one attribute, you have to make clear that they all share that same attribute. Either by fetching the values in your own routines and creating lists that are sortable (this would be the qs approach you mentioned) or by creating a common interface - which is this Model inheritance approach."
Adopted from question in stackoverflow