tags:

views:

37

answers:

3

I have some code that follows the example for multi-table inheritance as given on the documentation page: http://docs.djangoproject.com/en/dev/topics/db/models/#multi-table-inheritance. What I am trying to do is create a restaurant around a place.

I've already created a place, and I want to make a restaurant at it like so:

>>> p = Place.objects.get(id=12)
# If p is a Restaurant object, this will give the child class:
>>> p.restaurant
<Restaurant: ...>
>>> r = Restaurant(p)

but I just get this error:

TypeError: int() argument must be a string or a number, not 'Place'

I want to add more information to my models, so I don't want to go in and manually set all the fields to be equal. is there anyway to do this?

A: 

I think you should add a foreign key to Restaurant like so:

class Place(models.Model):
    name = models.CharField(max_length=50)
    address = models.CharField(max_length=80)

class Restaurant(models.Model):
    place = models.ForeignKey(Place)
    serves_hot_dogs = models.BooleanField()
    serves_pizza = models.BooleanField()

and then you can do:

>>> p = Place.objects.get(id=12)
>>> r = Restaurant(place=p)
patrick
Model inheritance adds an implicit OneToOne from the child to the parent. But you're close.
Ignacio Vazquez-Abrams
A: 

Is this thing, what do you want to do?

>>> r = Restaurant.objects.get(pk=p.pk)
yedpodtrzitko
This won't work because it's not yet a restaurant in the database.
Ignacio Vazquez-Abrams
+1  A: 

Unfortunately model "promotion" like this is problematic. The proper way is to create a new Restaurant object by copying the fields from Place. You have to do this by iterating through Place._meta.get_fields_with_model() and seeing which model the fields belong to. I can't give you the exact code for that, but if you can live with GPLed code then it's in transifex.txcommon.models since revision bcd274ce7815.

Ignacio Vazquez-Abrams
any chance you can provide a link to that somewhere?
Fred
http://code.transifex.org/index.cgi/mainline/file/a9f391a5c9b8/transifex/txcommon/models.py#l62
zellyn