我有以下模型父
class ModelParent(PolymorphicModel):
company = models.CharField(max_length=50)
.......
和模范 child
class ModelChild(ModelParent)
company = models.CharField(max_length=10, blank=True)
...........
我怎样才能让模型 child 公司属性覆盖父级 公司没有制作 的模型属性摘要父模型
最佳答案
这是 not possible不幸的是,没有抽象的父模型。
Field name “hiding” is not permitted
In normal Python class inheritance, it is permissible for a child class to override any attribute from the parent class. In Django, this isn’t usually permitted for model fields. If a non-abstract model base class has a field called author, you can’t create another model field or define an attribute called author in any class that inherits from that base class.
This restriction doesn’t apply to model fields inherited from an abstract model. Such fields may be overridden with another field or value, or be removed by setting field_name = None.
建议改为简单地创建一个属性或重命名子模型的字段。您可以做的另一件事是删除父模型的“公司”字段并将其移动到所有子模型。
class ModelChild(ModelParent)
child_company = models.CharField(max_length=10, blank=True)
...........
关于django - 从子模型覆盖父模型属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51772164/