Created
February 14, 2012 02:05
-
-
Save AndrewIngram/1822479 to your computer and use it in GitHub Desktop.
Trying to make it possible to override a Django model
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.loading import cache | |
from django.db.models.base import ModelBase | |
import sys | |
def override_model(app_label, model_name): | |
caller = sys._getframe(1) # Obtain calling frame | |
module_name = caller.f_globals['__name__'] | |
def decorator(orig_cls): | |
class MyModelBase(ModelBase): | |
def __new__(cls, name, bases, attrs): | |
attrs['__module__'] = module_name | |
if app_label in cache.app_models and model_name in cache.app_models[app_label]: | |
del cache.app_models[app_label][model_name] | |
cache._get_models_cache.clear() | |
return ModelBase.__new__(cls, name, bases, attrs) | |
class MyModel(object): | |
__metaclass__ = MyModelBase | |
return type(orig_cls.__name__, (MyModel, orig_cls), {}) | |
return decorator |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment