Rakesh babu
Rakesh babu

Reputation: 325

Unable to import models in __init__.py django 1.9.4

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?

Upvotes: 6

Views: 3450

Answers (1)

knbk
knbk

Reputation: 53649

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.

Upvotes: 4

Related Questions