6

My directory structure is.

Mypack:
  --> __init__.py
  --> admin.py
  --> apps.py
  --> foo.py
  --> models.py

In apps.py, I have AppConfig. I have some methods in foo.py which uses the models imported from models.py. and I imported all methods in init.py.

from foo import *

I make this app installable with pip. when I install it in other django app and try to run python manage.py check. it gives the following error.

django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

please suggest me, how to fix this issue?

Rakesh babu
  • 325
  • 6
  • 11
  • I imported my models with " from models import * " – Rakesh babu Mar 26 '16 at 08:17
  • show your `apps.py`, `__init__.py` / file where you imported foo – v1k45 Mar 26 '16 at 08:18
  • __init__.py: default_app_config = 'Mypack.apps.myConfig' from foo import * – Rakesh babu Mar 26 '16 at 08:20
  • apps.py: from django.apps import AppConfig class myConfig(AppConfig): name = 'mypack' verbose_name = "django mypack" – Rakesh babu Mar 26 '16 at 08:23
  • you cannot import models until the application is ready. why are you importing it in `__init__.py` file? do you want to access foo methods directly from package? – v1k45 Mar 26 '16 at 08:33
  • yes.. is there any possibility to import models in __init__.py to make all of my methods accessible from the package – Rakesh babu Mar 26 '16 at 09:40
  • Importing through `__init__.py` files can be a little tricky, butI think the answer you're looking for would be to follow the formula used [here](http://stackoverflow.com/a/583065/1842146). – Jordon Birk Mar 26 '16 at 10:17

1 Answers1

4

From the 1.9 release notes (emphasis mine):

  • All models need to be defined inside an installed application or declare an explicit app_label. Furthermore, it isn’t possible to import them before their application is loaded. In particular, it isn’t possible to import models inside the root package of an application.

You are (indirectly) importing your models into the root package of your app, Mypack/__init__.py. If you still want to import the functions in foo.py into your root package, you need to make sure that it doesn't import the models when the module is first imported. One option is to use inline imports:

def foo():
    from .models import MyModel
    MyModel.objects.do_something()

If importing the functions in your root package is not a hard requirement (e.g. for backwards compatibility), I would personally just stop importing them in __init__.py and change other imports to use Mypack.foo.

knbk
  • 52,111
  • 9
  • 124
  • 122