I have organized some of my app models into sub directories. Everything runs fine (i.e. the models are recognized for migrations etc.). But I’m curious on the best way to get a complete list of all models for all of my apps, including those within sub dirs. Not that the below doesn’t inculde sub dir models.
apps.get_models()
Can you provide a minimal example of what you’re trying? (Along with a more detailed description of your module layouts.)
What I’m mostly concerned about is where you’re trying to call that function.
From the docs for get_models at: Applications | Django documentation | Django
Requires the app registry to be fully populated.
If this is something you’re trying to use during the Django “start up” process, I can understand why you might not be getting complete results.
I don’t know if this is ‘best practice’.
But I ended up including model imports for any subfolders in the base apps.py like so:
class Config(AppConfig):
default_auto_field = "django.db.models.AutoField"
label = "XXX"
name = "apps.XXX.XXX"
@staticmethod
def imports():
import apps.XXX.signals # noqa
from apps.XXX.XXX import models # noqa
def ready(self):
self.imports()
I then ensure that when I’m going to loop through all models for that particular app, that I just call on the static imports method above. e.g.
app_config = apps.get_app_config('XXX')
app_config.imports()
models = app_config.get_models()
Which has solved this issue for me at the moment.