Skip to content

Instantly share code, notes, and snippets.

@AndrewIngram
Created February 14, 2012 02:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AndrewIngram/1822479 to your computer and use it in GitHub Desktop.
Save AndrewIngram/1822479 to your computer and use it in GitHub Desktop.
Trying to make it possible to override a Django model
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