Abstract model in Django

The basis of an abstract model is to avoid code repetition. Django development follows the DRY (Don't repeat yourself) principle, and that is exactly what the abstract model class is trying to implement. The abstract model class uses the model inheritance technique to do this. 

Generally, the abstract base classes are applied when we want to use the parent class to hold information that you don’t want to have to type out for each child model.  For example, imagine having two class models, namely User and Profile. The User model class is basically for authentication, while the Profile model class is for displaying on the user interface. 

Let's create the models like so:

models.py

class User(AbstractBaseUser):
username = models.CharField(unique=True, max_length=200)
email = models.EmailField(unique=True, max_length=255)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
date_created = models.DateTimeField(auto_now_add=True)

last_updated = models.DateTimeField(auto_now=True)

class Profile(Timestamped):

user = models.OneToOneField('account.User',on_delete=models.CASCADE)
avatar = models.URLField(blank=True)
   date_created = models.DateTimeField(auto_now_add=True)
last_updated = models.DateTimeField(auto_now=True)

def __str__(self):
return self.user.username

Based on the models, the date_created and last_updated fields are common in the User and Profile class models. We can use abstract base classes to avoid this repetition. 

Using Abstract base classes.

Using abstract base classes, we write our base class and put abstract=True in the Meta class. The models above can be represented in a non-repetitive manner like so:

class Timestamped(models.Model):
date_created = models.DateTimeField(auto_now_add=True)
last_updated = models.DateTimeField(auto_now=True)

class Meta:
abstract = True

class User(AbstractBaseUser, Timestamped):

username = models.CharField(unique=True, max_length=200)
email = models.EmailField(unique=True, max_length=255)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)

class Profile(Timestamped):

user = models.OneToOneField('account.User', on_delete=models.CASCADE)
avatar = models.URLField(blank=True)

def __str__(self):

return self.user.username

A new model, Timestamped , was created (base class) along with the common fields, date_created and last_updated .The two models, User and Profile , now have to inherit the properties of the Timesstamped model. We only have to declare  abstract=True  using Meta in the base class. 

In summary, the Abstract Model basically uses the inheritance technique to avoid code repetition.