How to compare fields within a Constraint

I am migrating some custom validation code into declarative Constraints.

As a minimal example:

class MyModel(Model):
    a = IntegerField()
    b = IntegerField()

I’d like to create a CheckConstraint that enforces that a > b.

The examples in the docs show only basic comparisons to static values, I was wondering if comparing between columns was also possible?

The possible Field lookups I’ve been reading about as options to a Q object:

It appears that F expressions may be the tool to use. If so, it might be helpful to add at least one small example to the Constraint docs for this.

It looks like the solution is:

    class Meta:
        constraints = [
            CheckConstraint(
                name="%(app_label)s_%(class)s_a_less_than_b",
                check=Q(a__lt=F("b")),
                violation_error_message="A must be less than B",
            ),
        ]

I’d still make the suggestion that a small example using F be added to the constraints docs.

1 Like