Django抽象模型字段取决于子级属性

时间:2019-09-12 06:31:06

标签: python django django-models model

我想编码一些模型结构,其中包含具有相同字段但名称,help_text和related_name不同的抽象父模型和子模型。如何更好和更短地实现这种行为?有什么解决办法吗?

class AbstractModel(models.Model):
    class Meta:
        abstract = True

    name = None
    code = None
    rel_field = models.OneToOneField(RelatedModel, on_delete=models.CASCADE,
                                     primary_key=True, related_name=code)
    field = models.CharField(name, null=True,
                             help_text=HELP_DICT.get(code, None))


class ChildOne(AbstractModel):
    name = "child one name"
    code = "one"


class ChildTwo(AbstractModel):
     name = "child two name"
     code = "two"
     child_field = SomeAnotherField()

我想做

ChildOne.field == models.CharField("child one name", help_text=HELP_DICT.get("one", None) ...)
ChildTwo.field == models.CharField("child two name", help_text=HELP_DICT.get("two", None) ...)

RelatedModel.one == ChildOne
RelatedModel.two == ChildTwo

0 个答案:

没有答案