How to create hierarchical parent/child relationships with specific permissions in an already build Django (DRF) app

I need to build out a data model in an already existing Django app that uses DRF and I am quite new to Django.

The rules are as follows:

  • There are ParentOrganizations and ChildOrganizations that Users can belong to.
  • A ParentOrganization can have many ChildOrganizations
  • An app user can can belong to many ChildOrganizations, but all ChildOrganizations they belong to, must belong to the same parent
    • There is a caveat here that internal super users will have access to all parent and child orgs
  • A app user can have different permissions on each ChildOrganization that they belong to.
  • We will use Django Admin to create users and assign them to their parent and child organizations along with the permissions for each child organization

A few questions and some code:

  1. This app already exists so it seems that I missed the boat on building out the custom user class without some hacky stuff. Does any of the above warrant extending the auth.User? I'm thinking this isn't necessary.
  2. Would the built in Django groups and roles be an okay way to accomplish this? I'm worried about getting locked into things as our use cases become more complex.
  3. Assuming I build this out custom how does this code look?
class ParentOrganization(models.Model):
    name = models.CharField(max_length=100)
    users = models.ForeignKey(User, on_delete=models.CASCADE)

class ChildOrganization(models.Model):
    parent = models.ForeignKey(ParentOrganization, on_delete=models.CASCADE)
    name = models.CharField(max_length=300)
    users = models.ForeignKey(User, on_delete=models.CASCADE)


class ChildOrganizationPermissions(models.Model):
    users = models.ForeignKey(User, on_delete=models.CASCADE)
    child_organization = models.OneToOneField(ChildOrganization, on_delete=models.CASCADE)
    can_view = models.BooleanField()
    can_order = models.BooleanField()
Back to Top