Search code examples
pythondjangodjango-modelsdjango-inheritance

How to provide a default value for base class attribute from subclass in Django?


Scenario:

class BaseClass(models.Model):
    base_field = models.CharField(max_length=15, default=None)

class SubClass(BaseClass):
    # TODO set default value if base_field's value is None
    ...

ie. I need to be able to load a fixture into the database, providing a default value only if the base_field is None. Any help greatly appreciated! (note: BaseClass is not abstract)


Solution

  • You could override the save method, check if base_field is set, otherwise set it to the default value.