Paul Cunnane
Paul Cunnane

Reputation: 33

Model subclass: override CharField max_length

I have a supplied database schema for which I want to create a Django application. Many of the tables in the schema share a common set of columns, such as name and date_created. That prompted me to create an abstract Standard_model class containing those columns, and subclass the relevant models from it.

Unfortunately, some of the tables have a name column with a different max_length. I'm trying to come up with a way for the subclassed model to pass the max_length value to the abstract base class, but I'm drawing a blank.

Any ideas?

class Standard_model(models.Model):
    name = models.CharField(max_length=50)
    date_created = models.DateTimeField()

    class Meta:
        abstract = True

class MyModel(Standard_model):
    name = models.CharField(max_length=80)  # Can't do this.

Upvotes: 2

Views: 814

Answers (1)

alecxe
alecxe

Reputation: 474181

No, you cannot override the name field definition:

In normal Python class inheritance, it is permissible for a child class to override any attribute from the parent class. In Django, this is not permitted for attributes that are Field instances (at least, not at the moment). If a base class has a field called author, you cannot create another model field called author in any class that inherits from that base class.

See also:

And, FYI, according to the model naming convention, it should be called StandardModel.

Upvotes: 2

Related Questions