skip to Main Content

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

Only users with role=='client' can have User.broker 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'...)

2

Answers


  1. Chosen as BEST ANSWER

    As Alek Yo stated, I can use CheckConstraint

    The working result:

    constraints = [
                CheckConstraint(
                    check=Q(broker__isnull=True) | Q(role=RoleChoices.CLIENT),
                    name="clients_only_can_have_broker",
                )
            ]
    

  2. I believe what you’re looking for is CheckConstraint

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search