Model Inheritance

Model Inheritance is one of the interesting features of Django. With this feature, you can define “base” models to be extended. For example, you may want to create some models that have timestamp or “logical delete” attribute (i.e is_deleted). Defining timestamp & is_deleted attributes in every model would be time-wasting. So, in Django you can define abstract models.

Abstract models are different with ordinary models. When syncdb command is executed, Django will not create database tables for those abstract models. Django will only create database tables for  explicit models that extend abstract models. This is useful. Very useful. Take a look at these code for example:

This is an abstract model.

#file: blog/core/models.py

from django.db import models

import datetime

class BaseModel(models.Model):

    timestamp = models.DateTimeField(auto_now_add = True)
    is_deleted = models.BooleanField(default = False)

    def save_upd(self):
        self.timestamp = datetime.datetime.utcnow()
        self.save()

    def delete_soft(self):
        self.is_deleted = True
        self.save_upd()

    class Meta:
        abstract = True

This is an example of a model that extends BaseModel.

#file: blog/user/models.py

from blog.core.models import BaseModel

class User(BaseModel):
    id_user = models.AutoField(primary_key = True)
    username = models.CharField(max_length = 200)
    password = models.CharField(max_length = 128)

    class Meta:
        db_table = 'user'

With that, User model will have id_user, username, password, timestamp, and is_deleted as attributes. That’s all. Very simple & useful, indeed.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s