如何覆盖父类中的字段 [英] How to override a field in the parent class
问题描述
我在Django模型中有父类和子类。我想在初始化子类时在父类中填充一个字段。或在子类中覆盖此字段。
I have parent and child classes in Django model. And I want to fill a field in parent class when initialize child class. Or override this field in child class.
class Parent(models.Model):
type = models.CharField()
class Child(Parent):
type = models.CharField() //Doesn't work
也尝试重写init方法,但它不工作。
Also trying override init method, but it doesn't work too. How can I accomplish this?
推荐答案
在正常的Python类继承中,允许子类重写父类的任何属性。在Django中,对于属于字段实例的属性(至少,目前不允许),不允许这样做。如果基类有一个名为author的字段,则不能在从该基类继承的任何类中创建另一个名为author的模型字段。
In normal Python class inheritance, it is permissible for a child class to override any attribute from the parent class. In Django, this is not permitted for attributes that are Field instances (at least, not at the moment). If a base class has a field called author, you cannot create another model field called author in any class that inherits from that base class.
你不能。 参考
这篇关于如何覆盖父类中的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!