[Answer]-Django models kind of multi-table inheritance not working

1👍

You don’t need to have ids in your models; Django handle it automatically. Also you’re not supposed to use camel case. In other words: personId should be person_id and is not necessary anyway – just remove it.

In general I avoid non-abstract inheritance with an ORM.

I don’t really understand what you want to achieve but I’d suggest 2 approaches (for Person, Alumni, Professor, etc.), depending on your needs:

1. Abstract inheritance:

class Person:
    class Meta:
        abstract = True

    # here you put all the common columns

Then:

class Alumni(Person):
    # the other columns - specific to alumn

etc.

By doing this you have one table per sub-type of Person: Alumn, Professor etc.

2. Use composition:

class Alumn:
     person = models.ForeignKey(Person, null=True, related_name="alumni_at")
     university = ...

class Professor:
     person = models.ForeignKey(Person, null=True, related_name="professor_at")
     university = ...

This way you can do:

bob = Person.objects.create(first_name="bob", ...)
Alumn.objects.create(person=bob, university="univ 1")
Professor.objects.create(person=bob, university="univ 2")
Alumn.objects.create(person=bob, university="univ 2")

Leave a comment