Last active
November 12, 2018 09:29
-
-
Save vskrachkov/949bf362327e3ce3e271cd7564e22b08 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
def discover(package_name): | |
"""Function that discovers packages for django. | |
For example, if you want store your models in different files you must | |
call this function in __init__ file of the models package. | |
Django app structure: | |
some_app/ | |
__init__.py | |
models/ | |
my_model.py | |
another_model.py | |
""" | |
from os import path | |
import glob | |
import importlib | |
# Find all the model names to be imported | |
modules = glob.glob(path.join(path.dirname(__file__), "*.py")) | |
names = [path.splitext(path.basename(n))[0] for n in modules] | |
names = [n for n in names if n != "__init__"] | |
# Determine the app name assuming appname/models/*.py structure | |
app = path.basename(path.abspath(path.join(__file__, '..', '..'))) | |
# Import each, assuming that e.g. Mymodel lives in models/mymodel.py | |
for name in names: | |
mpath = f'{app}.{package_name}.{name}' | |
importlib.import_module(mpath) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment