2

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.

1 Answers1

2

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.

Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • I already have - sorry, I thought that was clear. I'll edit the code sample to make it clearer. – Paul Cunnane Jan 28 '15 at 15:52
  • I was curious about this too. I didn't think it was possible and now I know for sure after your edit. But in the example above, not like it matters. Just make both length 80. – dan-klasson Jan 28 '15 at 15:59
  • @dan-klasson yup, but the problem is that there can be multiple models with different `max_length` value of the `name ` field. The solution would be to remove it from the `StandardModel` and define in every single class there it is needed. – alecxe Jan 28 '15 at 16:01
  • Yeah or just make all the fields for the different models what the maximum field is. Not like it matters much unless you have millions of rows. – dan-klasson Jan 28 '15 at 16:03