Django Reimport Module when tests.py is Run
I am working on a Django app that performs some class introspection ahead of time on all models.
This seems to work fine if those models are defined in models.py, but if I define them in my tests.py, __init__.py doesn't see those models.
The goal is to have a module level dictionary that is run once when __init__.py is loaded:
perms_dict = {}
for cls in Models.__subclasses__():
add some stuff to perms_dict
When running tests, this code block gets run twice, the first time it does not see the Models in tests.py, and a second time the tests.py models are seen. Unfortunately, when a function is called in the __init__.py file, it seem开发者_开发技巧s to use the perms_dict from the initial run for some reason, and does not include the models from tests.py.
The easiest solution is to import tests.py from within __init__.py so it is aware of those models, but obviously in actual use that would not be desirable.
The Git repo is available at: git://github.com/philipkimmey/django-cerberus.git
Thanks!
Your core task here seems to be running some code for each model exactly once. There's a good existing solution for this: class_prepared
signal from django builtins.
http://docs.djangoproject.com/en/1.3/ref/signals/#class-prepared
As for doing introspection ahead of time, this might be not desirable in some circumstances -- for example, when models classes are created dynamically. I'd recommend just loading models.py
initially and let the signal handler take care of remaining model classes once they are imported.
精彩评论