Django ORM seems not to permit constraints on ManyToManyField.
class Component(ComponentMetaData): class Type(models.IntegerChoices): Part = 0 Components = 1 type = models.IntegerField( choices=Type.choices, ) components = models.ManyToManyField( "self", blank=True, null=True, ) def clean(self) -> None: if self.type == 0 and self.components: raise ValidationError("Parts could not have components.") return super().clean() class Meta: constraints = [ models.CheckConstraint( check=( Q(type = 0) & Q(components__isnull = True) ) | ( Q(type = 1) # componenets only fields ), name = "components_enum" ) ]
Migration attempt with the above model results in the error below;
ERRORS: myapp.Component: (models.E013) 'constraints' refers to a ManyToManyField 'components', but ManyToManyFields are not permitted in 'constraints'.
Does anyone know why this is not permitted and what should one do if one would like to keep a ManyToManyField empty on some condition based on the values of other fields?