Inheritance Model, Polymorphism in Django

First of all, you need to install django-model-utils which allows you to create inheritance models.

ref. or

sudo pip install django-model-utils

Next, create your model.

from django.db import models
from model_utils.models import InheritanceCastModel

class Content(InheritanceCastModel):
    title = models.CharField(max_length=50)

class Video(Content):
    autoPlay = models.BooleanField(default=True)

class Audio(Content):
    Lyric = models.CharField(max_length=2000, null=True)


contents = Content.objects.all()
for content in contents:
    if hasattr(content, 'audio'):
        print 'This is audio'
        print 'This is video'

Also, you can add a filter as below.

list = Content.objects.filter(real_type__name = 'audio')

Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s