如何从现有的基本模型实例创建一个继承的django模型实例? [英] How can I create an inherited django model instance from an existing base model instance?
本文介绍了如何从现有的基本模型实例创建一个继承的django模型实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
class Place(models.Model):
name = models.CharField(max_length = 50)
address = models.CharField(max_length = 80)
class餐厅(Place):
serve_hot_dogs = models.BooleanField()
serving_pizza = models.BooleanField()
我以前创建了一个 Place
这个:
six_ave_street_vendor = Place(name ='Bobby Hotdogs',address ='6th Ave')
six_ave_street_vendor。保存()
现在,bobby已将街头卖家升级到餐厅。我该怎么做我的代码?
为什么这段代码不起作用:
six_ave_restaurant =餐厅(place = six_ave_street_vendor,
serving_hot_dogs =
serve_pizza = True)
six_ave_restaurant.save()
解决方案
这是我的解决方法:
six_ave_restaurant =餐厅(place_ptr = six_ave_street_vendor,
serving_hot_dogs = true,
serving_pizza = True)
six_ave_restaurant.save_base(raw = True)
如果你想用 six_ave_restaurant
做其他事情,你应该再次收到它,因为它的 id
不是分配给它,因为它在正常的 save()
之后被分配:
six_ave_restaurant = Restaurant.objects.get(id = six_ave_street_vendor.id)
I have two django models 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()
I had previously created a Place
instance, like this:
sixth_ave_street_vendor = Place(name='Bobby Hotdogs', address='6th Ave')
sixth_ave_street_vendor.save()
Now bobby has upgraded his street vendor to a restaurant. How can I do that in my code?! Why this code doesn't work:
sixth_ave_restaurant = Restaurant(place=sixth_ave_street_vendor,
serves_hot_dogs=True,
serves_pizza=True)
sixth_ave_restaurant.save()
解决方案
Here is my workaround:
sixth_ave_restaurant = Restaurant(place_ptr=sixth_ave_street_vendor,
serves_hot_dogs=True,
serves_pizza=True)
sixth_ave_restaurant.save_base(raw=True)
And if you want to do something else with sixth_ave_restaurant
, you should get it again, because its id
is not assigned yet, as it gets assigned after normal save()
:
sixth_ave_restaurant = Restaurant.objects.get(id=sixth_ave_street_vendor.id)
这篇关于如何从现有的基本模型实例创建一个继承的django模型实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文