How can I create an inherited django model instance from an existing base model instance?

别等时光非礼了梦想. 提交于 2020-01-15 01:23:25

问题


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

回答1:


You should use place_ptr instead of place.

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



回答2:


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)


来源:https://stackoverflow.com/questions/14034486/how-can-i-create-an-inherited-django-model-instance-from-an-existing-base-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!