如何从现有基础模型实例创建继承的django模型实例?

时间:2012-12-25 22:39:00

标签: django django-models django-inheritance

我有两个django模型like these

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()

我之前创建了一个Place实例,如下所示:

sixth_ave_street_vendor = Place(name='Bobby Hotdogs', address='6th Ave')
sixth_ave_street_vendor.save()

现在鲍比已将他的街头小贩升级为餐厅。我怎么能在我的代码中做到这一点?! 为什么这段代码不起作用:

sixth_ave_restaurant = Restaurant(place=sixth_ave_street_vendor,
                                  serves_hot_dogs=True,
                                  serves_pizza=True)
sixth_ave_restaurant.save()

2 个答案:

答案 0 :(得分:3)

您应该使用place_ptr代替place

restaurant = Restaurant.objects.create(place_ptr=sixth_ave_street_vendor,
                                       serves_hot_dogs=True, serves_pizza=True)

答案 1 :(得分:3)

以下是我的解决方法:

sixth_ave_restaurant = Restaurant(place_ptr=sixth_ave_street_vendor,
                                  serves_hot_dogs=True,
                                  serves_pizza=True)
sixth_ave_restaurant.save_base(raw=True)

如果你想用sixth_ave_restaurant做其他事情,你应该再次获得它,因为它的id尚未分配,因为它是在正常save()之后分配的:

sixth_ave_restaurant = Restaurant.objects.get(id=sixth_ave_street_vendor.id)