[Answered ]-Queryset for mutiple table joins

1👍

You can filter with:

Organization.objects.filter(
    Department_Org__Project_Dept__UserProjectRole_Module__user=my_user
)

However the related_name=… values [Django-doc] are cumbersome: these are names to access the related objects that point to an object. Your UserProjectSubscriptionRole is also a junction model of a ManyToManyField. You can rewrite the modeling to:

class Department(models.Model):
    org = models.ForeignKey(Organization, on_delete=models.PROTECT, related_name='departments')
    # …

class Project(models.Model):
    dept = models.ForeignKey(Department, on_delete=models.PROTECT, related_name='projects', null=True)
    # …

class Subscription(models.Model):
    project = models.ForeignKey(Project, on_delete=models.PROTECT, related_name='subscriptions')
    # …

class User(AbstractBaseUser, PermissionsMixin):
    # …
    projects = models.ManyToManyField(
        Project,
        trough='UserProjectSubscriptionRole',
        related_name='users'
    )

class UserProjectSubscriptionRole(models.Model):
    user = models.ForeignKey(User, on_delete=models.PROTECT, related_name='userprojectroles')
    project = models.ForeignKey(Subscription, on_delete=models.PROTECT, related_name='userprojectroles')
    role = models.ForeignKey(RoleType, on_delete=models.PROTECT, related_name='userprojectroles')

Then you can filter with:

Organization.objects.filter(
    departments__projects__users=my_user
)

This seems more readable and compact.

Leave a comment