Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django, multi-table inheritance is that bad?

This isn't really specific to django.

One can model

Place (with location, name, and other common attributes)
 - Restaurant  (menu..)
 - ConcertHall  (hall size..)
  1. in two separate tables and let each one hold all the fields they need. (in django world, this is called abstract inheritance)
  2. in three tables, where one holds the common fields and the other two has their own unique fields. (multi-table inheritance in django)

The authors of book Two scoops of Django 1.8 strongly advise against using multi-table inheritance.

Say you want to query places based on it's location and paginate the results (It doesn't have to be a location, can be any other common attribute we want to filter on)

I can see how I can achieve it using Multi-table inheritance.

select place.id from place LEFT OUTER JOIN "restaurant" on ( restuarant.id=place.id) LEFT OUTER JOIN "concerthall" on ( concerthall.id=place.id) where ... order by distance

Is it feasible to do it with abstract inheritance?

like image 765
eugene Avatar asked Oct 18 '25 01:10

eugene


1 Answers

According to Django documentation: Model inheritance:

The only decision you have to make is whether you want the parent models to be models in their own right (with their own database tables), or if the parents are just holders of common information that will only be visible through the child models.

I think both possibilities are just tools, equally good tools and it just depends on your use case for their appropriateness. Surely there are specific things to consider for both approaches, and conceptually sometimes multi-table inheritance may be more difficult to comprehend, but other than that this topic just turns to become opinionated.

If you need a single queryset for both models, then it is logical that you consider multi-table inheritance rather than abstract models, because otherwise you would need to get into combining two querysets into one, most probably by using lists as this relevant answer suggests, but you would definitely lose ORM functionality.

like image 93
Wtower Avatar answered Oct 20 '25 08:10

Wtower



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!