简体   繁体   English

如何在Django项目的其他模块中正确导入模型?

[英]How to correctly import models in extra modules in Django project?

If i want to use some model in extra file in my Django project, i can't do it by this simple way: 如果我想在Django项目的额外文件中使用某些模型,则无法通过以下简单方法进行操作:

from myproject_app.models import *

because i get this error: 因为我收到此错误:

django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

To solve this problem, I found this solution: 为了解决这个问题,我找到了这个解决方案:

import os
import django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings")
django.setup()
from myproject_app.models import *

Ok. 好。 It works. 有用。 But if i want to use any fuction from this extra file in models.py project does not start at all! 但是,如果我想从models.py项目中的这个额外文件使用任何功能,则根本无法启动!

Please help me. 请帮我。

i think you forgot to register your app in, 我认为您忘记了注册应用程序,

INSTALLED_APPS = (
    myproject_app,
)

将您创建的所有应用程序添加到INSTALLED_APPS,并且由于PEP8透视图永远不会通过“ *”导入所有模型,而是根据您使用的名称单独导入

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM