Search code examples
djangoinheritancedjango-modelsdjango-model-field

Override Field Option on Inherited Model in Django


I've found similar questions and answers, but none seems exactly right. I've got an abstract base model like so:

class BaseModel(models.Model):
    timestamp = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)
    description = models.CharField(max_length=512, blank=True, null=True, help_text='Help')

    class Meta:
        abstract = True

And then I'm inheriting from it:

class AnotherModel(BaseModel):
    field1 = models.CharField(max_length=512)

But I want this model's help_text on the description field to be something else, like help_text='Some other help text'

What's the best way to do this? Can I override options on fields from inherited models?


Solution

  • If this is really about the help text, I suggest to just override the ModelForm. However, you can use a factory and return the inner class:

    def base_factory(description_help: str = "Standard text"):
        class BaseModel(models.Model):
            timestamp = models.DateTimeField(auto_now_add=True)
            modified = models.DateTimeField(auto_now=True)
            description = models.CharField(
                max_length=512, blank=True, null=True, help_text=description_help
            )
    
            class Meta:
                abstract = True
    
        return BaseModel
    
    
    class ConcreteModel(base_factory("Concrete help")):
        field1 = ...