Meta class inheritance with constraints

Hi, everyone

I have a question.

I created a model with two classes: an abstract base class and a child class.
I want to use inheritance in the meta class and extend it in the child class.

class Person(models.Model):
    # ...
    class Meta:
        abstract = True
        constraints = [
            models.CheckConstraint(
                name="check_1",
                check=Q(...)
            )
            models.CheckConstraint(
                name="check_2",
                check=Q(...)
            )
        ]


class Student(Person):
    # ...
    class Meta(Person.Meta):
        pass

In this way, constraints are also available in the Student class. I would like to
add an additional constraint in the child class. That’s why the child
in the meta class I created a constraint “constraints = […]”.

class Student(Person):
    # ...
    class Meta(Person.Meta):
        constraints = [
            models.CheckConstraint(
                name="check_3",
                check=Q(...)
            )
        ]

However, this overrides the parent’s “constraints = […]” variable. This is how I tried it
bypass:

class Student(Person):
    # ...
    class Meta(Person.Meta):
        constraints = Person.Meta.constraints
        constraints += [
            models.CheckConstraint(
                name="check_3",
                check=Q(...)
            )
        ]

And that’s how all three restrictions work now.

My question is, is this method any good? Or should it be done differently?
Thank you all in advance for your help.

It works? Yes? It’s good.

Mechanically, there are many ways to do this. (e.g., Using the append method instead of +=.)

But overall, what you’re doing seems to me to be at least as good as any of the alternatives I can think of.

Thanks Ken

Since I didn’t see a description/instructions for this anywhere, I made this up.
I was just wondering how others have solved this.

1 Like