Sitemap
Dharma Teja K

Dharma Teja K

Great learnings gives you better opportunities to grow

Django Abstract classes

2 min readJul 24, 2022
Press enter or click to view image in full size
Django abstract classes

Abstract classes are reusable components. You can inherit them in models wherever you want to get the features from abstract base class. You can define as many abstract classes and inherit them into single model. In database, no table will be created for abstract classes but abstract class fields will be existed in inherited models

Get Dharma Teja K’s stories in your inbox

Join Medium for free to get updates from this writer.

Every abstract class look like a normal django models but only the difference is abstract=True keyword in abstract class Meta

For demonstration, I am going to create two models Product and Order and two abstract classes Userstamp and Timestamp

Userstamp includes only information, who created what and who is updated what

Timestamp includes, what created at what time and what is updated at what time

Create Product and Order models and inherit from Userstamp and Timestamp. You don’t need to mention models.Model specifically

Now let’s observe the database schema for the created models

Press enter or click to view image in full size
All tables in database schema

Here you can’t see the tables for Userstamp and Timestamp because they are defined as abstract=True. The tables will be create only for the models which are inherited from abstract classes

Press enter or click to view image in full size
Expand view of Order and Product tables

You can see here, created_by, updated_by, created_at and updated_at in both Product and Order models and we did not define any of these fields in the models

Find the full project here

--

--

Dharma Teja K
Dharma Teja K

Written by Dharma Teja K

Great learnings gives you better opportunities to grow