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()
现在当你创建一个 Restaurant
时,你会自动创建一个 Place
,这很好,也是我期望和想要的行为.
Now when you create a Restaurant
, you automatically make a Place
, which is fine, and the behaviour I expect and want.
但是,如果我创建了一个 Place
,然后我决定要转换为特定类型(例如 Restaurant
),该怎么办?如何使用现有的 Place
创建 Restaurant
?
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屋!