Inheritance Model, Polymorphism in Django

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

ref. http://pypi.python.org/pypi/django-model-utils or https://github.com/carljm/django-model-utils/blob/master/README.rst

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)

Try

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

Also, you can add a filter as below.

list = Content.objects.filter(real_type__name = 'audio')
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