Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to create Abstract Model Class in Django?
We will learn about how to create Abstract Model Class in Django.
An abstract model class in Django is a model that serves as a template for other models to inherit from rather than being directly created or saved to the database. Abstract models allow you to define common fields and behaviors shared across multiple models in your application. In Django, you create an abstract model by defining a class that inherits from django.db.models.Model and setting abstract = True in its Meta class.
When a model inherits from an abstract model, it gains all the fields and methods of the abstract class, but no separate database table is created for the abstract model itself. This promotes code reusability and helps maintain consistency across related models.
Abstract models can define fields, methods, and metadata like standard models. You can use Django's field classes such as CharField, IntegerField, and ForeignKey to define fields. Custom methods can implement specific behaviors like computed properties, validation, or custom queries.
In Django, inheritance from abstract models follows the same principles as regular Python inheritance. Subclasses inherit all fields and methods from the abstract parent class and can override or extend them as needed. When creating concrete models that inherit from abstract models, ensure the abstract attribute is not set to True.
Steps to Create Abstract Model Class
Step 1 Create a new class that inherits from
django.db.models.Model. Choose a descriptive name that reflects the purpose of your abstract model.Step 2 Define common fields and attributes that your concrete models should inherit. Include fields like
CharField,DateField,TextField, and any custom methods or properties.Step 3 Add a Meta inner class to your abstract model with
abstract = True. This tells Django not to create a separate database table for this model.Step 4 Create concrete model classes that inherit from your abstract model. Define additional fields and methods specific to each concrete model.
Step 5 Run migrations to create the necessary database tables for your concrete models.
Example 1: Timestamped Model
In this example, we create an abstract model class that provides timestamp functionality. The AbstractTimestampedModel contains created_at and updated_at fields that are automatically populated ?
from django.db import models
class AbstractTimestampedModel(models.Model):
# Time when the record is created
created_at = models.DateTimeField(auto_now_add=True)
# Time when the record is updated
updated_at = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
class ArticleModel(AbstractTimestampedModel):
# name of the article
name = models.TextField()
# author of the article
author = models.TextField()
class Meta:
db_table = 'myapp_articlemodel'
After creating the models, run the following commands to create and apply migrations ?
python manage.py makemigrations python manage.py migrate python manage.py shell
Create and save a record to test the abstract model inheritance ?
>>> from myapp.models import ArticleModel
>>> article = ArticleModel(name='Tutorialspoint Article', author='ABC XYZ')
>>> article.save()
>>> article = ArticleModel.objects.first()
>>> print("Article name:", article.name)
>>> print("Author:", article.author)
>>> print("Created At:", article.created_at)
>>> print("Updated At:", article.updated_at)
Example 2: User Model Base
This example demonstrates using the same abstract model across multiple concrete models. The AbstractUserModel provides common user fields that both student and employee models can inherit ?
from django.db import models
class AbstractUserModel(models.Model):
name = models.TextField()
dob = models.TextField()
class Meta:
abstract = True
class StudentModel(AbstractUserModel):
roll = models.IntegerField()
class Meta:
db_table = 'myapp_studentmodel'
class EmployeeModel(AbstractUserModel):
employeeNo = models.IntegerField()
class Meta:
db_table = 'myapp_employeemodel'
After running migrations, create and test records for both models ?
>>> from myapp.models import StudentModel, EmployeeModel
>>> student = StudentModel(name='ABC Student', dob='01/01/2023', roll=123)
>>> student.save()
>>> employee = EmployeeModel(name='XYZ Employee', dob='12/12/2023', employeeNo=111)
>>> employee.save()
>>> student = StudentModel.objects.first()
>>> employee = EmployeeModel.objects.first()
>>> print("Student - Name:", student.name, "DOB:", student.dob, "Roll:", student.roll)
>>> print("Employee - Name:", employee.name, "DOB:", employee.dob, "Employee No:", employee.employeeNo)
Key Benefits
Code Reusability Define common fields once and use across multiple models
Consistency Ensure similar models follow the same structure and behavior
Maintainability Changes to common functionality only need to be made in the abstract model
Clean Architecture Separates common concerns from model-specific logic
Conclusion
Abstract model classes in Django provide an excellent way to share common fields and behaviors across multiple models while maintaining clean, maintainable code. By using abstract models, you can eliminate code duplication and ensure consistency throughout your application's data layer.
