Add a CheckConstraint for a related object field in Django models

Viewed 357

I've two Django models:

class A(models.Model):
    is_pure = models.BooleanField()

class B(models.Model):
    a = models.ForeignKey(A, on_delete=models.CASCADE)

    class Meta:
        constraints = [
            models.CheckConstraint(
                check=models.Q(a__is_pure=True),
                name="a_is_pure"
            )
        ]

I want to add a constraint that no B instance can have a reference to an A instance that its is_pure field is False. When I add the above code, make migrations, and try to migrate, I get this error:

(models.E041) 'constraints' refers to the joined field 'a__is_pure'.

Does Django support such thing currently ? If not, what do you recommend?

0 Answers
Related