Django: how to create a custom "base" model

In almost all of my tables (= classes models.Model

), I have three DateTimeField

:

  • Creature
  • validity
  • validity

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

+3


source to share


2 answers


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.

+11


source


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

+2


source







All Articles