Model Inheritance in Django
Models inheritance works the same way as normal Python class inheritance works, the only difference is, whether we want the parent models to have their own table in the database or not. When the parent model tables are not created as tables it just acts as a container for common fields and methods.
There are three styles of inheritance possible in Django.
- Abstract base classes : Use this when the parent class contains common fields and the parent class table is not desirable.
- Multi-table inheritance : Use this when the parent class has common fields, but the parent class table also exists in the database all by itself.
- Proxy models : Use this when you want to modify the behavior of the parent class, like by changing
orderby
or a new model manager.
Abstract base classes
When we run makemigrations
for the above model changes, only Address
model changes will be there. Please note that in the Meta
class of TimestampedModel
we have put abstract=True
, this tells Django, not to create a database table for the corresponding table.
Migration
Going forward if we inherit from the TimestampedModel
, that would by default add created_at
and updated_at
, with this, we achieve DRY (Don't Repeat Yourself)
and a cleaner way to code.
childClass
now has a nice method to soft-delete objects. Let’s see, how it works.
Now Let’s open the django shell by running command python manage.py shell
.
Multi-table Inheritance
In the above example of Address
class, although it is inheriting from multiple parent tables, it is still an example of the abstract base class inheritance
style, since both the parent classes are abstract in nature.
For multi-table inheritance
, parentClass's
table also gets created in the database. The name multi-table
comes from the fact that multiple tables actually gets created in the database and not because the childClass
is inheriting multiple parentClass
.
Again, Open the Django Shell python manage.py shell
Now, when we will create a Place
instance, it will also create an entry for address
in the database.
Here you can see, 1 entry for address also got created.
Source Code. github