如何覆盖父类中的一个字段 [英] How to override a field in the parent class
问题描述
class Parent(models.Model):
type = models.CharField()
class Child(Parent):
type = models.CharField()//不起作用
还尝试重写init方法,但它也不起作用。
如何实现这一点?
在普通的Python类继承中,子类允许从父类覆盖任何属性。在Django中,对于Field实例的属性(至少不在当前),不允许这样做。如果基类有一个名为author的字段,则不能在继承该基类的任何类中创建另一个名为author的模型字段。
你不行参考
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
Also trying override init method, but it doesn't work too. How can I accomplish this?
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.
You can't. Reference
这篇关于如何覆盖父类中的一个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!