在 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/数据库/模型/#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?
推荐答案
更新的答案:正如人们在评论中指出的那样,原始答案没有正确回答问题.事实上,只有 LongNamedRestaurant
模型在数据库中创建,Place
没有.
Updated answer: as people noted in comments, the original answer wasn't properly answering the question. Indeed, only the LongNamedRestaurant
model was created in database, Place
was not.
一个解决方案是创建一个代表地方"的抽象模型,例如.AbstractPlace
,并继承它:
A solution is to create an abstract model representing a "Place", eg. AbstractPlace
, and inherit from it:
class AbstractPlace(models.Model):
name = models.CharField(max_length=20)
rating = models.DecimalField()
class Meta:
abstract = True
class Place(AbstractPlace):
pass
class LongNamedRestaurant(AbstractPlace):
name = models.CharField(max_length=255)
food_type = models.CharField(max_length=25)
另请阅读@Mark answer,他很好地解释了为什么您不能更改从非-抽象类.
Please also read @Mark answer, he gives a great explanation why you can't change attributes inherited from a non-abstract class.
(请注意,这仅在 Django 1.10 之后才有可能:在 Django 1.10 之前,无法修改从抽象类继承的属性.)
(Note this is only possible since Django 1.10: before Django 1.10, modifying an attribute inherited from an abstract class wasn't possible.)
自 Django 1.10 它是可能!你只需要按照你的要求去做:
Original answer
Since Django 1.10 it's possible! You just have to do what you asked for:
class Place(models.Model):
name = models.CharField(max_length=20)
rating = models.DecimalField()
class Meta:
abstract = True
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)
这篇关于在 Django - 模型继承 - 它是否允许您覆盖父模型的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!