Skip to content

Instantly share code, notes, and snippets.

@coderanger
Created May 12, 2010 00:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coderanger/398055 to your computer and use it in GitHub Desktop.
Save coderanger/398055 to your computer and use it in GitHub Desktop.
A subclass to allow splitting Django models into a package without manually specifying app_label for every one.
from django.db.models import base
from django.conf import settings
class ModelBase(base.ModelBase):
def __new__(cls, name, bases, attrs):
parents = [b for b in bases if isinstance(b, ModelBase)]
if not parents:
# Don't run our fixup on the model base class itself.
return super(ModelBase, cls).__new__(cls, name, bases, attrs)
old_module = attrs['__module__']
for installed_app in settings.INSTALLED_APPS:
if old_module.startswith(installed_app):
attrs['__module__'] = installed_app+'.models'
break
else:
raise ValueError('Unable to find appropriate app label for model %r', name)
return super(ModelBase, cls).__new__(cls, name, bases, attrs)
class Model(base.Model):
__metaclass__ = ModelBase
class Meta:
abstract = True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment