3

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()
Reza Mohammadi
  • 645
  • 5
  • 13

2 Answers2

5

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)
Reza Mohammadi
  • 645
  • 5
  • 13
3

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)
Fatih Erikli
  • 2,986
  • 2
  • 15
  • 11
  • I Set both `place_ptr` and `place_ptr_id`, but django still tries to insert a new Place :( – Reza Mohammadi Dec 25 '12 at 23:05
  • @RezaMohammadi that might be because `sixth_ave_street_vendor` is not yet saved, and looking into your code you haven't called the save method `sixth_ave_street_vendor.save()` – Aamir Rind Dec 25 '12 at 23:15
  • Here is another way: Create a model that called `BasePlace`, and extend the other models with that model. – Fatih Erikli Dec 25 '12 at 23:17