Created
May 12, 2010 00:09
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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