简体   繁体   中英

Use custom join query with Django ManyToMany relationship

I have a User model which connects to a Role model via a ManyToMany, and then the Role model connects to two models, SitePermission or ForumPermission . Problem is, I can't figure out how to setup that connection.

Here are my models, with (I believe) irrelevant fields removed.

Role:

class Role():
    class RoleTypes(models.TextChoices):
        SITE = "s", "Site"
        FORUM = "f", "Forum"

    role_type = models.CharField(max_length=1, choices=RoleTypes.choices, null=True)
    permissions = models.ManyToManyField(
        "permissions.Permission",
        related_name="roles",
        through="permissions.RolePermissions",
    )

RolePermissions:

class RolePermissions():
    role = models.ForeignKey("permissions.Role", on_delete=models.PROTECT)
    permission = models.ForeignKey("permissions.SitePermission", on_delete=models.PROTECT)

SitePermissions:

class SitePermissions():
    permission = models.CharField(max_length=64)

ForumPermissions:

class SitePermissions():
    permission = models.CharField(max_length=64)
    forum = models.ForeignKey(
        "forums.forum", db_column="forumId", on_delete=models.PROTECT
    )

Problem of course, is that I can't connect multiple tables to the ManyToMany. If I was doing it in SQL, I'd have something like roles r LEFT JOIN role_permissions rp_s ON r.type = 's' and r.id = rp.role_id INNER JOIN site_permissions sp ON rp_s.permission_id = sp.id with a second set of joins for forum_permissions (I know that SQL isn't exactly right, more for example).

So is there a way to accomplish this? Conditionally link to multiple tables? Or do I need to have a separate property in Role for each SitePermission and ForumPermission , and then have logic for each to utilize it?

try

RolePermissions.objects.raw("roles r LEFT JOIN role_permissions rp_s ON r.type = 's' and r.id = rp.role_id INNER JOIN site_permissions sp ON rp_s.permission_id = sp.id")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM