ExclusionConstraint with expression does not apply migration

Hello,

I’m setting up an exclusion constraint on through model to ensure that we do not accidentally add multiple offerings with overlapping products to an agency. However when i use “reference__fk_id”, I get the error “fk_id” does not exist.


class AgenceSubscription(models.Model):
    agence = models.ForeignKey(Agence, on_delete=models.CASCADE)
    sub_group = models.ForeignKey(SubscriptionGroup, on_delete=models.CASCADE)

    class Meta:
        ordering = ["agence"]
        constraints = [
            ExclusionConstraint(
                name="exclude_overlapping_subscriptions",
                expressions=[
                    ("agence", RangeOperators.EQUAL),
                    ("sub_group__product_config", RangeOperators.EQUAL),
                ],
            ),
        ]

here product_config is a FK to another table.

Aren’t expression allowed on ExclusionConstraint ? Or is this not supported?

:wave: @vazark !

Database constraints cannot span across tables.

We have system checks in place to ensure that built-in constraint classes (e.g. CheckConstraints and UniqueConstraints) respect this limitation but since is a contrib abstraction ExclusionConstraint uses a different format to store reference to expressions it’s not covered by them.

In order so solve this issue I believe that Model._check_constraints should be changed to call a new Constraint.check method that encapsulate all the logic required to validate each Constraint subclasses. This new entrypoint could then be used by ExclusionConstraint to validate the members of its specialized expressions collection.