Django使用相关密钥加入查询

时间:2018-04-25 09:21:05

标签: python django django-models

我有这个型号:

class Role(models.Model):
    role_name = models.CharField()

class RolePriviledge(models.Model):
    role = models.ForeignKey(Role, related_name='role_priviledge' )        
    module_name = models.CharField()
    priviledge_level = models.CharField()

class UserRole(models.Model):
    user = models.ForeignKey(User)
    role = models.ForeignKey(Role)

我要做的是找到指定用户的所有权限。在sql中,这将是:

SELECT t3.* 
FROM UserRole t1
JOIN Role t2 on t1.role_id = t2.id
JOIN RolePriviledge t3 on t2.id = t3.role_id
WHERE t1.user_id = USER_ID

(我也可以使用Role跳过加入,只需在UserRoleRolePriviledge之间进行内部联接

我如何与Django ORM一起加入? UserRole.objects.filter(user_id=USER_ID).select_related('role')UserRole加入Role。如何将其加入RolePriviledge

1 个答案:

答案 0 :(得分:2)

使用backward relation

privileges = []
user_roles = UserRole.objects.filter(user__id=USER_ID)

for user_role in user_roles:
    privileges.append(user_role.role.role_priviledge.all())

privilegeslist个Querysets。