Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save eculver/370026 to your computer and use it in GitHub Desktop.

Select an option

Save eculver/370026 to your computer and use it in GitHub Desktop.
Examples of how to implement inheritance with Django models
"""Examples of how to implement inheritance with Django models.
Idea here is DRY (don't repeat yourself). If models are similar, let them
share functionality to the extent that its ancestrty makes sense.
It's important to note is that because of the "abstract = True", Django knows
not to create tables for those models, and instead only creates tables for
those models that implement those abstract base classes.
It can also be noted that instead of having one gigantic, monolithic models.py
file, one can make models a module of itself:
myapp/
models/
__init__.py
abstract.py
item.py
element.py
views.py
urls.py
...
And then, magically, in myapp/models/__init__.py:
from myproj.myapp.models.abstract import *
from myproj.myapp.models.item import *
from myproj.myapp.models.element import *
This establishes a sense of organization and maintainability within the app
when models.py grows to be quite large, or really, in general.
This article is also helpful for automatically setting created_by/modified_by
on save: http://haineault.com/blog/101/
"""
# optionally: base.py
class Base(models.Model):
title = models.CharField(max_length=255)
# User references
created_by = models.CharField(max_length=100)
modified_by = models.CharField(max_length=100)
deleted_by = models.CharField(max_length=100)
# Time references
created_date = models.DateTimeField(auto_now_add=True)
modified_date = models.DateTimeField(auto_now=True)
deleted_date = models.DateTimeField(null=True, db_index=True)
class Meta:
abstract = True
# optionally: item.py
class Item(Base):
item_field1 = models.CharField(max_length=100)
item_field2 = models.CharField(max_length=200)
class Meta:
abstract = True
class PinkItem(Item):
pink_item_field1 = models.CharField(max_length=100)
pink_item_field2 = models.CharField(max_length=200)
class RoundItem(Item):
round_item_field1 = models.CharField(max_length=100)
round_item_field2 = models.CharField(max_length=200)
# optionally: element.py
class Element(Base):
element_field1 = models.CharField(max_length=100)
element_field2 = models.CharField(max_length=200)
class Meta:
abstract = True
class RedElement(Element):
red_element_field1 = models.CharField(max_length=100)
red_element_field2 = models.CharField(max_length=200)
class GreenElement(Element):
green_element_field1 = models.CharField(max_length=100)
green_element_field2 = models.CharField(max_length=200)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment