Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: how to create custom "base" model

Tags:

In almost all my tables (= classes of models.Model) I have three DateTimeField:

  • creation
  • validity start
  • validity end

Is there a way to have a "base" model class where I declare those fields, and make all my other model extend this one? I couldn't find a valuable answer on the Web.

like image 347
Olivier Pons Avatar asked Jul 27 '15 07:07

Olivier Pons


People also ask

What is custom model in Django?

The default User model in Django uses a username to uniquely identify a user during authentication. If you'd rather use an email address, you'll need to create a custom User model by either subclassing AbstractUser or AbstractBaseUser .

What is __ init __ method do in models?

__init__ method "__init__" is a reseved method in python classes. It is called as a constructor in object oriented terminology. This method is called when an object is created from a class and it allows the class to initialize the attributes of the class.


1 Answers

You need to create an abstract base class having these common fields and then inherit this base class in your models.

Step-1: Create a new Abstract Base Class

We first create an abstract base class called BaseModel. This BaseModel class contains the 3 model fields creation_date, valididity_start_date and validity_end_date which are common in almost every model of yours.

In the inner Meta class, we set abstract=True. This model will then not be used to create any database table. Instead, when it is used as a base class for other models, its fields will be added to those of the child class.

class BaseModel(models.Model):  # base class should subclass 'django.db.models.Model'      creation_date = models.DateTimeField(..) # define the common field1     validity_start_date = models.DateTimeField(..) # define the common field2     validity_end_date = models.DateTimeField(..) # define the common field3      class Meta:         abstract=True # Set this model as Abstract 

Step-2: Inherit this Base class in your models

After creating the abstract base class BaseModel, we need to inherit this class in our models. This can be done using normal inheritance as done in Python.

class MyModel1(BaseModel): # inherit the base model class      # define other non-common fields here     ...  class MyModel2(BaseModel): # inherit the base model class      # define other non-common fields here     ... 

Here, MyModel1 and MyModel2 classes contain the 3 fields creation_date, valididity_start_date and validity_end_date from the base class BaseModel apart from the other model fields defined in it.

like image 116
Rahul Gupta Avatar answered Sep 21 '22 03:09

Rahul Gupta