Search code examples
djangopython-3.xdjango-modelsdjango-apps

How to make models of app available to other apps in a django project?


It seems like to be best practice (or at least one common way) to create a Django 3 based fullstack project which uses project specific Django apps (instead of standalone Django apps) with a structure like this (refer to e.g. here):

fullstack_project/
  frontend/
    ... # frontend stuff goes into here
  backend/  # Django project name
    apps/
      app1/
        apps.py
        logic.py
        models.py
        ...
      app2/
        apps.py
        logic.py
        models.py
      ...
    wsgi.py
    ...
  manage.py

The apps (here: app1) are integrated in the most basic form (no ruls, views, etc.) via fullstack_project/backend/apps/app1/apps.py

class App1Config(AppConfig):
    name = 'backend.apps.app1'

and fullstack_project/backend/settings.py

INSTALLED_APPS = [
    ...
    'backend.apps.app1.apps.App1Config',
    'backend.apps.app2.apps.App2Config',
]

Using logic of one app (e.g. app2/logic.py) in another app (e.g. app1/logic.py) works just fine (e.g. via from backend.apps.app2.logic import ... in app1/logic.py).

However if I try to access the models of app1 in the logic of app2 I get django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.. I could implement a database wrapper for an app to allow cross-app database access. However ass the apps are cross-project anyway I'd like to avoid that and allow access more easily. How can I fix this issue?


Solution

  • It is possible that there will be some code in __init__.py which is trying to access DB even before the app is registered and ready. so if you have any code in __init__.py comment it or make sure it will access database once the app is ready.