Django: how to create a custom "base" model
You need to create an abstract base class with these common fields, and then inherit this base class in your models.
Step 1. Create an Abstract Base Class
First, let's create an abstract base class BaseModel
. This class BaseModel
contains 3 model fields creation_date
, valididity_start_date
and validity_end_date
, which are common to almost every of your models.
In the inner class, Meta
we set abstract=True
. This model will 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 the fields 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 an abstract base class, BaseModel
we need to inherit this class in our models. This can be done using regular inheritance, as is 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 classes MyModel1
and MyModel2
contain 3 fields creation_date
, valididity_start_date
and validity_end_date
from the base class BaseModel
, besides other model fields defined in it.
source to share
class Basetable(models.Model):
created_on = models.DateTimeField(auto_now_add=True)
modified_on = models.DateTimeField(auto_now=True)
created_by = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='%(class)s_createdby')
modified_by = models.ForeignKey(settings.AUTH_USER_MODEL,
related_name='%(class)s_modifiedby', null=True, blank=True)
class Meta:
abstract = True
This way you can define your model and extend Basetable to another model class
source to share