Django constraints - only users with specific role can have specific field set (not null)

Trying to figure out if and how can I set conditional constraints like this:

Only users with role=='client' can have field not null.

Is it possible to do that using Meta.contstraints or a different mechanism that will take care of that?

User model:

class User...:
    role = CharField(...)
    broker = ForeignKey('User'...)

I believe what you're looking for is CheckConstraint

As Alek Yo stated, I can use CheckConstraint

The working result:

constraints = [
                check=Q(broker__isnull=True) | Q(role=RoleChoices.CLIENT),
Back to Top