1

I am using Multi-Table inheritance (aka Concrete Inheritance), where I have a non-abstract model + DB Table called Clients, which is concerned with common details concerning all the clients.

But a client can be an Individual, Partnership or Company, for which I have created inheriting models and tables. An Individual has first name + last name, and company has other specific particulars, etc.

I want to be able to access the names of clients (derived from the columns from the child tables) when I want a list of all clients.

After lot of searching, I found that this tutorial, works successfully.

Basically, it involves inserting a column on the Client table, which will store the name of the Child model. Then using that name, the appropriate child model is identified and appropriate child method is accessed.

But it seems to be a slightly cumbersome way to implement polymorphism in Multi-Table inheritance.

I want to know whether since 2012, Django has introduced any better way to deal with the issue, or is this still the only way?

Please let me know if my code sample is required, but the link provided has a beautiful example already.

Chinmay Kamat
  • 193
  • 2
  • 19

1 Answers1

3

There is django-model-utils application with Inheritance Manager. It will cast automatically your parent class to children instances. Example from docs:

from model_utils.managers import InheritanceManager

class Place(models.Model):
    # ...
    objects = InheritanceManager()

class Restaurant(Place):
    # ...

class Bar(Place):
    # ...

nearby_places = Place.objects.filter(location='here').select_subclasses()
for place in nearby_places:
    # "place" will automatically be an instance of Place, Restaurant, or Bar

Also check this question for generic solution with ContentType. And also check awesome article by Jeff Elmore about this topic. Quite old, but still great.

Community
  • 1
  • 1
valignatev
  • 6,020
  • 8
  • 37
  • 61