Django模型继承:使用现有的超类创建一个子类 [英] Django model inheritance: Create a subclass using existing super class
问题描述
我正在使用多表 - 继承,并想知道如何从超类的实例创建一个继承类型。
I'm using multi-table-inheritance, and want to know how to create an inherited type from an instance of the superclass.
使用文档中给出的示例:
Using the example given in the documentation:
class Place(models.Model):
name = models.CharField(max_length=50)
address = models.CharField(max_length=80)
class Restaurant(Place):
serves_hot_dogs = models.BooleanField()
serves_pizza = models.BooleanField()
现在,当您创建一个餐厅
时,您自动做一个地方
,这是很好的,我期望和想要的行为。
Now when you create a Restaurant
, you automatically make a Place
, which is fine, and the behaviour I expect and want.
但是,如果我做 Place
,稍后决定我要转换为特定类型(例如 Restaurant
)。如何使用现有的 Place
创建一个餐厅
?
But what if I make a Place
, and later decide I want to convert to a specific type (like Restaurant
). How do you create a Restaurant
, using an existing Place
?
推荐答案
多表继承只是Place和Restaurant之间的 OneToOneField
关系。
Multi-table inheritance is just OneToOneField
relation between Place and Restaurant.
place = Place.objects.get(id=1)
# Create a restaurant using existing Place
restaurant = Resturant(place_ptr=place)
restaurant.save()
这篇关于Django模型继承:使用现有的超类创建一个子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!