To enable efficient routing and sharding, every model belonging to a tenant must include a tenant column (e.g., account_id). This allows queries to include the tenant ID in the WHERE clause, enabling the database to quickly locate all records for a specific account.
For standard models
Add a ForeignKey to the tenant model directly to the child model.
class Task(models.Model):
name = models.CharField(max_length=255)
project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='tasks')
# Add the tenant column
account = models.ForeignKey(Account, related_name='tasks', on_delete=models.CASCADE)
For ManyToMany models
To distribute ManyToManyField relationships, you must use an explicit through model that includes the tenant column. This ensures that queries involving the relationship can be routed via the account_id.
class Project(models.Model):
name = models.CharField(max_length=255)
account = models.ForeignKey(Account, related_name='projects', on_delete=models.CASCADE)
# Use a 'through' model
managers = models.ManyToManyField(Manager, through='ProjectManager')
class ProjectManager(models.Model):
project = models.ForeignKey(Project, on_delete=models.CASCADE)
manager = models.ForeignKey(Manager, on_delete=models.CASCADE)
# Include the tenant column in the through model
account = models.ForeignKey(Account, on_delete=models.CASCADE)
class Task(models.Model):
name = models.CharField(max_length=255)
project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='tasks')
account = models.ForeignKey(Account, related_name='tasks', on_delete=models.CASCADE)
class Project(models.Model):
name = models.CharField(max_length=255)
account = models.ForeignKey(Account, related_name='projects', on_delete=models.CASCADE)
managers = models.ManyToManyField(Manager, through='ProjectManager')
class ProjectManager(models.Model):
project = models.ForeignKey(Project, on_delete=models.CASCADE)
manager = models.ForeignKey(Manager, on_delete=models.CASCADE)
account = models.ForeignKey(Account, on_delete=models.CASCADE)