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 is used as a template for other models to inherit from rather than one that is meant to be created or saved to the database. In an application, similar fields and behaviours shared by several models can be defined using abstract models. With Django, you define a model class that derives from Django.db.models to establish an abstract model class.

Model and set True for the abstract attribute. The attributes and methods of this abstract class will be inherited by any model that derives from it, but no new database table will be created.

Abstract models can define fields, methods, and metadata like standard models. The many field classes supplied by Django, including CharField, IntegerField, and ForeignKey, can be used to describe fields. Methods can be created to implement specific behaviours, such as computed properties, custom queries, or validation.

In Django, inheritance from abstract models adheres to the same guidelines as conventional models. All the fields and methods declared in the superclass are inherited by subclasses, which can replace or add to them as necessary. The abstract attribute shouldn't be set to True when developing a new model derived from an abstract model.

To use an abstract model in a Django application, it must be a part of one of the installed apps, and any new database tables or fields must be created by running the required migrations.

Steps to Create Abstract Model Class

  • Step 1 ? Set up a new class inherited from django.db.models. Your abstract model class uses a model. This class can have any name you like, but a name that accurately describes what it does in your application is a good idea.

  • Step 2 ? Provide any qualities or standard fields your concrete models should inherit from the abstract model class. This can include any custom methods or attributes you wish all of your models to have and fields like CharField, DateField, TextField, etc.

  • Step 3 ? Your abstract model class should have a Meta inner class added to it, with the abstract attribute set to True. Django is informed that as this is an abstract model class, a separate database table should not be built for it.

  • Step 4 ? Provide the concrete model classes from your abstract model class. Each concrete model's additional variables and actions can be defined as necessary.

  • Step 5 ? Execute the migrations to build the database tables your concrete models require.

By building an abstract model class, you can specify standard fields and behaviours shared across various models in your application. Increasing the reuse of code and avoiding duplication can assist you in writing more maintainable code.

Example 1

In this example, we will create an Abstract Model class in Django and use it to understand it better. In the models.py file, we first create our abstract class named ?AbstractTimestampedModel', which holds two fields named ?created_at' and'updated_at'. By default, these field values will be populated with the current time if nothing is mentioned. We have created another model named ?ArticleModel', which takes the abstract model in the parameter and uses those fields. It contains two fields, ' name' and ?author'.

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 both classes, we need to run the following commands ?

python manage.py makemigrations
python manage.py migrate
python manage.py shell

Then we need to run the command to add a record in the database and print its values. Creating a record by the following commands ?

>>> from myapp.models import ArticleModel                                                                             >>> article = ArticleModel(name='Tutorialspoint Article', author='ABC XYZ')
>>> article.save()

After that, we need to print the values of the inserted record by the following commands ?

>>> from myapp.models import ArticleModel
>>> article = ArticleModel.objects.first()
>>> print("Article name: ", article.name, "\nAuthor: ", article.author, "\nCreated At: ", article.created_at, "\nUpdated At: ", article.updated_at)

Output

Example 2

In this example, we use a similar approach to create an abstract model, but here we use the same abstract model in two separate models. The abstract model name is ?AbstractUserModel', which stores the user's name and date of birth. Our two models are ?StudentModel' and ?EmployeeModel'. StudentModel has a rolling field, and EmployeeModel has an employeeNo field.

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'

The same steps must be performed to migrate these database models. After performing those steps, do the following to create and print the records.

>>> 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("Name: ", student.name, "\nDOB: ", student.dob, "\nRoll: ", student.roll)
>>> print("Name: ", employee.name, "\nDOB: ", employee.dob, "\nEmployee No: ", employee.employeeNo)

Output

Updated on: 2023-05-11T14:38:02+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements