In my Python 3.9, Django 3.2 project, I have this general folder structure
- manage.py
cbapp
models
- __init__.py
- vendor.py
- user_preferences.py
In my init.py file, I have all my model entries listed out ...
from .vendor import Vendor
from .user_preferences import UserPreferences
...
Each model class, e.g. Vendor, has this general sturcture
from django.db import models
class Vendor(models.Model):
...
Every time I add a new model I have to add a line into my init.py file. Is there any way I can write my init.py file so that it will just auto-import new files I add into my models directory?
CodePudding user response:
What you're looking for is some fancy dynamic imports, such as these.
If your model names are always the same pattern on your module names, the following code in init.py will probably work:
import os, glob
path = os.path.dirname(__file__)
modules = [os.path.basename(f)[:-3] for f in glob.glob(path "/*.py")
if not os.path.basename(f).startswith('_')]
stripped_path = os.path.relpath(path).replace('/', '.')
imports = {}
for module in modules:
model_name = module.title().replace("_", "")
imports[model_name] = getattr(__import__(stripped_path "." module, fromlist=[model_name]), model_name)
print(imports)
globals().update(imports)