在Django - 模型继承 - 它允许您覆盖父模型的属性? [英] In Django - Model Inheritance - Does it allow you to override a parent model's attribute?

查看:191
本文介绍了在Django - 模型继承 - 它允许您覆盖父模型的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找这样做:

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 called author, you cannot create another model field called author in any class that inherits from that base class.

这篇关于在Django - 模型继承 - 它允许您覆盖父模型的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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