我有这个型号:
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
跳过加入,只需在UserRole
和RolePriviledge
之间进行内部联接
我如何与Django ORM一起加入? UserRole.objects.filter(user_id=USER_ID).select_related('role')
会UserRole
加入Role
。如何将其加入RolePriviledge
?
答案 0 :(得分:2)
privileges = []
user_roles = UserRole.objects.filter(user__id=USER_ID)
for user_role in user_roles:
privileges.append(user_role.role.role_priviledge.all())
privileges
是list
个Querysets。