如何获取查询集的外键对象?

时间:2013-04-24 20:29:58

标签: python django django-models

我有三个模型Project,Member,User

class Project
    members = ManyToManyField(User, through="Member")

class User
    #...user model...

class Member
    project = ForeignKey(Project)
    user = ForeignKey(User)
    isAdmin = BooleanField(default=False)

如果我想获得项目的所有用户对象(p),我可以做p.members。但是,如何轻松获取项目的所有管理员(用户对象)?

Member.filter(project=p, isAdmin=True) # this gets all the admin member objects
# how to convert this to user objects?

1 个答案:

答案 0 :(得分:0)

User.objects.filter(member__isAdmin=True, member__project=p)

Django docs - Lookups that span relationships