如何覆盖父类中的一个字段 [英] How to override a field in the parent class

查看:104
本文介绍了如何覆盖父类中的一个字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Django模型中有父类和小孩类。我想在初始化子类时填入父类中的一个字段。或者在子类中覆盖此字段。

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆