本文介绍了无法在__init__.py django 1.9.4中导入模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目录结构是

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

在apps.py中,我有AppConfig。我在foo.py中有一些方法,该方法使用从models.py导入的模型。然后将所有方法导入 init .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 *

我使该应用可通过pip安装。当我在其他Django应用中安装它并尝试运行python manage.py check时。会出现以下错误。

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.

请建议我,如何解决此问题?

please suggest me, how to fix this issue?

推荐答案

摘自 (强调我的):

您(间接)将模型导入应用程序的根包 Mypack / __ init __。py 。如果您仍然想将 foo.py 中的函数导入到根包中,则需要确保在首次导入模块时不导入模型。一种选择是使用内联导入:

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()

如果在根包中导入函数不是很困难(例如,为了向后兼容),我个人将只是停止将它们导入 __ init __。py 并将其他导入更改为使用 Mypack.foo

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.

这篇关于无法在__init__.py django 1.9.4中导入模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 10:03