Group by Foreign Key and show related items - Django

前端 未结 2 1328
离开以前
离开以前 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.

    0 讨论(0)
  • 2020-12-28 18:46

    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.

    0 讨论(0)
提交回复
热议问题