how to associate existing parent with child in django multitable inheritance

1.7k Views Asked by At

I have an existing parent entity with many existing records:

class Entity(models.Model):
    name = models.CharField('Name', max_length=64, db_index=True) 

I also have child objects that extend using django multi table inheritance:

class Investor(Entity):
    investor_name = models.CharField(max_length=255)

I want to create new Investor objects that maybe existing Entities.

How do I associate and create Investors with existing Entities?

2

There are 2 best solutions below

2
On BEST ANSWER

I found a way you can do this like:

child = Restaurant(place_ptr=place)
child.save_base(raw=True)

You can view the full thread here: https://code.djangoproject.com/ticket/7623

0
On

You can't do this because

multi-table inheritance uses an implicit OneToOneField to link the child and the parent

This means there is a one-to-one relationship between the Entity named record and the corresponding subclassed Investor models. Django just handles the translation of it from multiple tables to a single model so you don't really notice it.

So when you create a Investor you have to write the following line

Investor.objects.create(investor_name ='jone', name='entity name')

Which will create a Investor table row associated with a Entity row with one to one relationship. So if you want to create a new Investor object with that existing Entity record then database one-to-one relationship violation will be occurred and so far no any other association syntax in Django for multi inheritence. For more details you can see this link

You can use existing Entity model record if your database design like below:

class Investor(models.Model):
  entity = model.ForeignKey(Entity) // Many-to-One relationship
  investor_name = models.CharField(max_length=255)