2

I am using Django with Django-Rest-Framework (no forms, no django_admin). I have the following models

class Company(models.Model):
    ...


class Sector(models.Model):
    ...
    company_id = models.ForeignKey(Company)
    employees = models.ManyToManyField(Employee)


class Employee(models.Model):
    ...
    company_id = models.ForeignKey(Company)

Employee can be in multiple Sectors and a Sector can have multiple Employees. (ManyToMany).

I want to add a constraint employee.company_id == sector.company_id in order to add a record into the Many2Many table.

I can do this validation in the serializers from the DRF, but I also want to handle this on the model level.

I added a through table in the ManyToManyField

class Sector(models.Model):
    ...
    company_id = models.ForeignKey(Company)
    employees = models.ManyToManyField(Employee, through='M2MTable')


class M2MTable:
    ...

    def save():
        # employee.company_id and sector.company_id validation is done here

This will handle saving an M2MTable object, but however this will not handle related object references Sector.employees.add(Employee)

From here I found out I can achieve this with m2m signals.

Is there another way of handling this

SWater
  • 384
  • 1
  • 13

0 Answers0