在Django - 模型继承 - 它允许您覆盖父模型的属性? [英] In Django - Model Inheritance - Does it allow you to override a parent model's attribute?
问题描述
我正在寻找这样做:
class Place(models.Model):
name = models.CharField(max_length=20)
rating = models.DecimalField()
class LongNamedRestaurant(Place): # Subclassing `Place`.
name = models.CharField(max_length=255) # Notice, I'm overriding `Place.name` to give it a longer length.
food_type = models.CharField(max_length=25)
这是我想要的版本使用(虽然我可以接受任何建议):
http://docs.djangoproject.com/en/dev/topics/db/models/#id7
This is the version I would like to use (although I'm open to any suggestion): http://docs.djangoproject.com/en/dev/topics/db/models/#id7
Django中是否支持此功能?如果没有,有没有办法实现类似的结果?
Is this supported in Django? If not, is there a way to achieve similar results?
推荐答案
不,它不是:
不允许字段名称隐藏
在普通的Python类继承中,允许一个小孩
类覆盖父类的任何属性。在Django中,对于Field
实例(至少
)的属性,不允许此
。如果一个基类有一个名为作者
的字段,那么
无法在任何一个中创建另一个名为作者
的模型字段
从该基类继承的类。
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 is not permitted for attributes that are
Field
instances (at least, not at the moment). If a base class has a field calledauthor
, you cannot create another model field calledauthor
in any class that inherits from that base class.
这篇关于在Django - 模型继承 - 它允许您覆盖父模型的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!