Unable to import models in __init__.py django 1.9.4

后端 未结 1 1997
甜味超标
甜味超标 2021-01-18 08:38

My directory structure is.

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

In apps.py, I

相关标签:
1条回答
  • 2021-01-18 09:24

    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.

    0 讨论(0)
提交回复
热议问题