Multiple models - One common primary key (Django) Multiple models - One common primary key (Django) django django

Multiple models - One common primary key (Django)


When you make Parent.objects.get(pk=1) you are getting Child1 and Child2 rows alright, but django ORM is returning you Parent instances, since it's only retrieving the data stored on the parent table.

To get an instance of the children model, you have to do parent_instance.childmodelname.

This can get messy real quick if you have multiple child classes, since you have to know exactly to which child model the parent instance belongs to, to be able to access it (if you try, for example, to access parent.child1 being a Child2 instance, it will raise an exception).

I recommend you use the django-model-utils app, which defines a custom manager called InheritanceManager which you can use on your model and will take care of retrieving and returning the corresponding child model instance, making the whole process a lot easier.