How to override a field in the parent class

早过忘川 提交于 2019-12-04 18:32:10

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/6897730/how-to-override-a-field-in-the-parent-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!