Group by Foreign Key and show related items - Django

前端 未结 2 1331
离开以前
离开以前 2020-12-28 18:33

I have the following models:

class Company(CachedModel):
    name = models.CharField(max_length=255)

class UserExtendedProfile(CachedModel):

    company =          


        
2条回答
  •  忘掉有多难
    2020-12-28 18:41

    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.

提交回复
热议问题