Group by Foreign Key and show related items - Django

こ雲淡風輕ζ 提交于 2019-12-30 01:06:40

问题


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


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/12731897/group-by-foreign-key-and-show-related-items-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!