首页 > 解决方案 > 覆盖 Django 中继承模型的字段选项

问题描述

我发现了类似的问题和答案,但似乎没有一个是完全正确的。我有一个像这样的抽象基础模型:

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

然后我继承它:

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

但我希望这个模型help_textdescription球场上是别的东西,比如help_text='Some other help text'

最好的方法是什么?我可以覆盖继承模型中的字段选项吗?

标签: djangoinheritancedjango-modelsdjango-model-field

解决方案


如果这真的是关于帮助文本,我建议只覆盖 ModelForm。但是,您可以使用工厂并返回内部类:

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 = ...

推荐阅读