Ограничения ManyToManyField
Django ORM, похоже, не допускает ограничений на 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"
)
]
Попытка миграции с вышеупомянутой моделью приводит к следующей ошибке;
ERRORS:
myapp.Component: (models.E013) 'constraints' refers to a ManyToManyField 'components', but ManyToManyFields are not permitted in 'constraints'.
Кто-нибудь знает, почему это не разрешено и что делать, если хочется оставить поле ManyToManyField пустым при некотором условии, основанном на значениях других полей?