Python 无法从 Django 中的另一个应用程序导入模型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43847173/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 23:26:32  来源:igfitidea点击:

Cannot import models from another app in Django

pythondjangodjango-apps

提问by darkhorse

so I have 2 apps running in the same project.

所以我在同一个项目中运行了 2 个应用程序。

My files are structured as follows:

我的文件结构如下:

/project_codebase
    /project
        __init.py
        settings.py
        urls.py
        wsgi.py
        ...    
    /app1
        ...
    /app2
        ...
    manage.py

So, I for some weird reason have a different name for my base directory (that is, it ends with codebase). Hopefully, that is not an issue.

因此,出于某种奇怪的原因,我的基本目录使用了不同的名称(即以代码库结尾)。希望这不是问题。

In my settings.py, I have this:

在我的settings.py 中,我有这个:

INSTALLED_APPS = [
    ...

    'app1',
    'app2',
]

Ok, so in my models.py (from app2), I can easily import models from app1 with from app1.models import *, however, when I use from app2.models import *in my models.py (from app1), I get an ImportError.

好的,所以在我的models.py(来自 app2)中,我可以轻松地从 app1 导入模型from app1.models import *,但是,当我from app2.models import *在我的models.py(来自 app1)中使用时,我得到了一个 ImportError。

Any solutions to this?

有什么解决办法吗?

回答by jojo

This might be due to circular importissues. To avoid this you should load the model dynamically:

这可能是由于循环导入问题。为避免这种情况,您应该动态加载模型

For recent versions of django (1.7+)use the application registry:

对于最新版本的 django (1.7+),请使用应用程序注册表

from django.apps import apps
MyModel1 = apps.get_model('app1', 'MyModel1')

For earlier django versions (<1.7):

对于较早的 Django 版本 (<1.7)

from django.db.models.loading import get_model
MyModel1 = get_model('app1', 'MyModel1')

Note 1:If you want to define a ForeignKey relationship, there is no need for a separate import statement. Django has you coveredon this:

注1:如果要定义一个ForeignKey关系不需要单独的import语句。Django为您介绍了这一点:

If app1is an installed app, you should define the ForeignKey relationship as follows:

如果app1是已安装的应用程序,则应按如下方式定义 ForeignKey 关系:

# in app2.py
class MyModel2(models.Model):
   mymodel1 = models.ForeignKey('app1.MyModel1')

Note 2: The get_modelonly works if app1is an installed app and MyModel1is the model you want to import from app1.

注 2get_model唯一适用app1于已安装的应用程序并且MyModel1是您要从中导入的模型app1

Note 3:Try to avoid wildcard import (from ... import *), as this is bad practice.

注意 3:尽量避免通配符导入 ( from ... import *),因为这是不好的做法

回答by vishes_shell

It's definitely a circular import.

这绝对是一个循环导入。

But i think is what you need is to use models as some sort of RetationFields(ForeignKey, ManyToManyFieldor OneToOneField) arguments. So you need to skip import and use as so:

但我认为这是你需要的是使用模型作为某种RetationFields(中ForeignKeyManyToManyFieldOneToOneField)参数。所以你需要跳过导入和使用:

# app1/models.py
class Model1(models.Model):
    relation_field = models.ForeignKey('app2.Model2')

From docs:

文档

If you need to create a relationship on a model that has not yet been defined, you can use the name of the model, rather than the model object itself

To refer to models defined in another application, you can explicitly specify a model with the full application label

如果需要在尚未定义的模型上创建关系,可以使用模型的名称,而不是模型对象本身

要引用在另一个应用程序中定义的模型,您可以明确指定具有完整应用程序标签的模型

Just put strobject as first argument to relation fields that leeds to <app_name>.<Model_name>.

只需将strobject 作为第一个参数放在导致<app_name>.<Model_name>.

Note: it's better to avoid importing everything from module(from <module_name> import *)

注意:最好避免从 module( from <module_name> import *)导入所有内容

回答by Ahmed Ginani

If you want to import only some specific module then do not use import *.

如果您只想导入某些特定模块,请不要使用import *.

It will take more time load your all library and so can affect the speed of your app also.

加载所有库需要更多时间,因此也会影响应用程序的速度。

If you want to use few modules from your second app then just add module name instead of whole libraries something like this:

如果您想使用第二个应用程序中的几个模块,那么只需添加模块名称而不是整个库,如下所示:

from app2.models import Module1, Module2

or it may be circular import issue as other clarify.

或者它可能是其他澄清的循环导入问题。

Thanks.

谢谢。

回答by youssef hassoun

i use this code always and it's work :)

我总是使用这个代码,它的工作:)

from position_app.models import Member

from position_app.models import Member

回答by Terry

You need to specify the model names you want to import, for ex from app1.models import ModelName1, ModelName2.

您需要指定要导入的模型名称,例如from app1.models import ModelName1, ModelName2.

回答by Catalina Libuy

It is a circular import

这是一个循环导入

In my case I needed the imported class not for a relation field, but for use it inside a method instead. If that's the case, I suggest to import inside the method, otherwise an AppRegistryNotReady("Models aren't loaded yet.") is raised.

在我的情况下,我需要导入的类不是用于关系字段,而是用于在方法中使用它。如果是这种情况,我建议在方法内部导入,否则会引发 AppRegistryNotReady("Models are not loaded yet.") 。

class Student(CustomUser):
""" Usuario alumno """
class Meta:
    verbose_name = "Alumno"
    verbose_name_plural = "Alumnos"

def get_current_school_class(self):
    """ Obtiene el curso actual de un alumno """
    from school.models import SchoolClass, StudentClass
    # proceed with the method...

回答by Markus

Make sure there is no name clash between one of your apps and one of the modules installed in your Python environment. If you use pip, you can run pip freezeto see a list of installed modules.

确保您的应用程序之一与 Python 环境中安装的模块之一之间没有名称冲突。如果您使用 pip,您可以运行pip freeze以查看已安装模块的列表。

I had the same error when one of my apps was named 'packaging', and the packaging python module was installed.

当我的一个应用程序被命名为“打包”并且安装了打包 python 模块时,我遇到了同样的错误。

回答by MD.JULHAS HOSSAIN

I also face this problem when I try to import my model from another app in (django2.2)

当我尝试从 (django2.2) 中的另一个应用程序导入我的模型时,我也遇到了这个问题

But at last I Imported It and Its successfully working.

但最后我导入了它并且它成功地工作了。

here is my two app:

这是我的两个应用程序:

INSTALLED_APPS = [
    ...

    'categories',
    'videos',
]

and this is the code for how I Imported it into videos/models.pyfile as a ForeignKeyConnectivity

这是我如何导入到代码视频/ models.py文件作为ForeignKey的连接

from django.db import models

class Videos(models.Model):
    categories = models.ForeignKey('categories.Categories', related_name='categories', on_delete=models.CASCADE)

If want to see my Categories Model from categories/models.pyfile, you can check this code otherwise neglect it

如果想从category/models.py文件中查看我的类别模型,您可以检查此代码,否则忽略它

from django.db import models

class Categories(models.Model): 
    category_name = models.CharField(max_length=50)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)