How to extend Django groups for dynamic user types?

Viewed 170

I have a SaaS project which many companies will use and within the companies there will be employees which will be applied to one of two groups: Supervisor or Non-Supervisor. This will probably look as such:

class EmployeeGroup(Group):
    ....

Each company will be able to create their own EmployeeType which falls into one of the EmployeeGroups. e.g. an EmployeeType may be Food and Beverage Supervisor which is an EmployeeGroup: Supervisor:

class EmployeeType(models.Model):
    ....
    employee_type = models.CharField(
        max_length=32,
        default='Server'
    )
    employee_group = models.ForeignKey(
        EmployeeGroup,
        null=True
    )
    company = models.ForeignKey(
        Company,
        on_delete=models.CASCADE,
        null=True
    )

And obviously each User will have an EmployeeType:

class User(AbstractUser):
    ....

    employee_type = models.ManyToManyField(
        EmployeeType,
        null=True,
    )

In this situation, can several companies share EmployeeGroups without sharing EmployeeTypes? My concern is that if an EmployeeType: Server is created at Company A then Company B will not be able to create an EmployeeType: Server as well. Or that if they do then information will get crossed. It wuold help to have an understanding of how the database works but I do not. Any links to external resources specific to this situation would be greatly appreciated!

1 Answers

To simplify and facilitate your requests to DB you may add one more column in your Company table, and write in it every new employee_groups when a new employee is hired:

class Company(models.Model):
    ...
    employee_groups = models.ManyToMany(EmployeeGroup, null=True)


class User(models.Model):
    _job = models.ForegnKey(Company, null=True)
    employee_type = models.ManyToManyField(
        EmployeeType,
        null=True,
    )

    def __setattr__(self, attrname, val):
        if attrname == 'job' and isinstance(val, Company):
            val.employee_groups.add(self.employee_type.employee_group)
            self._job = val

Now when you will set to some user a new job, that in company wich hire them will added a new employee_group.

After that you can easy get all employee_groups in any company you want by simple request:

employee = Users.objects.get(some_user_pk)
empoyer = Company.objects.get(some_company_pk)
employee.job = employer

print(empoyer.employee_groups)   # will contain employee_group of new employee
Related