Tuesday, January 3, 2017

Re: Multi-table Inheritance: How to add child to parent model?

Thanks Malik for the link to https://dateutil.readthedocs.io/en/stable/examples.html#relativedelta-examples
After many, many hours of being baffled at how to create a child instance from an existing parent, this answered my question.

On Thursday, June 23, 2016 at 12:45:23 AM UTC+2, Malik Rumi wrote:
This thread is obviously very old, but since it helped me find the answer, I thought I would share that for the benefit of others mystified by the lack of information on https://docs.djangoproject.com/en/1.9/topics/db/models/#multi-table-inheritance.

It turns out that although Derek's link to the docs was way out of date (the page does not exist anymore) his solution was still close to correct. The full documentation can be found here: https://docs.djangoproject.com/en/1.9/topics/db/examples/one_to_one/



On Thursday, November 4, 2010 at 1:25:25 PM UTC-7, Nan wrote:
I have an existing model that I want to extend using multi-table
inheritance.  I need to create a child instance for each parent
instance in the database, but I can't figure out how.  I've scoured
google and haven't come up with anything other than Ticket #7623[1].
Here are some of the things I've tried...

Let's adapt the Place / Restaurant example from the docs:

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

class Restaurant(Place):
    place = models.OneToOneField(Place, parent_link=True,
related_name='restaurant')
    serves_hot_dogs = models.BooleanField()
    serves_pizza = models.BooleanField()

I want to do the following, in essence:

for place in Place.objects.all():
  restaurant = Restaurant(**{
    'place': place,
    'serves_hot_dogs': False,
    'serves_pizza': True,
  })
  restaurant.save()

Of course, doing this tries to also create a new Place belonging to
the new Restaurant, and throws an error because no values have been
specified for the name and address fields.  I've also tried:

for place in Place.objects.all():
  restaurant = Restaurant(**{
    'serves_hot_dogs': False,
    'serves_pizza': True,
  })
  place.restaurant = restaurant
  place.save()

This, however, doesn't create any records in the restaurant table.

Any suggestions?

[1] http://code.djangoproject.com/ticket/7623

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/d3839315-8605-4717-90b8-b841b79573dc%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment