When using TenantForeignKey attribute, while creating migrations using makemigrate , foreign key is being created using both tenant column and primary key of the referenced table
If referencing table does not have a unique constraint, constraint creation fails
While creating migrations either a unique constraint could be generated or we can add a direction in documentation to add unique constraint into all tables which include tenant columns
class Project(TenantModel):
name = models.CharField(max_length=255)
account = models.ForeignKey(
Account, related_name="projects", on_delete=models.CASCADE
)
managers = models.ManyToManyField(Manager, through="ProjectManager")
employee = models.ForeignKey(
Employee,
related_name="projects",
on_delete=models.SET_NULL,
null=True,
blank=True,
)
tenant_id = "account_id"
#-------------------------------
# This block should be added either manually or automatically
class Meta:
constraints = [
models.UniqueConstraint(fields=['id', 'account_id'], name='unique_project_account')
]
# ---------------------------------
def __str__(self):
return "{} ({})".format(self.name, self.account)
class ProjectManager(TenantModel):
project = TenantForeignKey(
Project, on_delete=models.CASCADE, related_name="projectmanagers"
)
manager = models.ForeignKey(Manager, on_delete=models.CASCADE)
account = models.ForeignKey(Account, on_delete=models.CASCADE)
tenant_id = "account_id"
When using TenantForeignKey attribute, while creating migrations using makemigrate , foreign key is being created using both tenant column and primary key of the referenced table If referencing table does not have a unique constraint, constraint creation fails
While creating migrations either a unique constraint could be generated or we can add a direction in documentation to add unique constraint into all tables which include tenant columns