How do I add a database constraint in a Many-to-Many Relation

I have the following model:

class School(models.Model):
    principal = models.OneToOneField(User, on_delete=models.CASCADE)

The User model is Django's stock auth model. I want to only allow a school.principal to be instances of the User model that belongs to the Principals group. (By group, I also mean Django's stock auth Group model).

I'm basically stuck on how the implementation of check should be:

class School(models.Model):
    principal = models.OneToOneField(User, on_delete=models.CASCADE)

    class Meta:
        constraints = [
            models.CheckConstraint(
                check=<allow_only_User_instances_that_belongs_to_the_Principals_group>,
                name='principal_is_actually_a_principal',
            ),
        ]

On the chance that a database/Django version specific implementation is necessary, I'm using the following stack:

  • Python 3.8
  • Django 3.1
  • PostgreSQL 12.1

I know I can add the check on the application level, but having database constraints makes me feel confident that my data is always in valid state. Any help or nudge to the right direction will be greatly appreciated.

Thanks!



Read more here: https://stackoverflow.com/questions/64949939/how-do-i-add-a-database-constraint-in-a-many-to-many-relation

Content Attribution

This content was originally published by Alcher at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: