在Django python中导入模型 [英] Importing models in Django python

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

问题描述

如何在INSTALLED_APPS中的settings.py中导入所有模型?当我尝试插入某些模型时,发生错误:没有名为app1_model的模型"

How can I import all models in the settings.py in INSTALLED_APPS? When i`m trying to insert some model there is an error occurred: "no models named app1_model"

-ProjectName
--ProjectName
---models
----__init__.py
----admin.py
----app_1_model
----....
----app_n_model
---templates
---__init__.py
---settings.py
---urls.py
---wsgi.py
--manage.py

^项目结构^

推荐答案

INSTALLED_APPS适用于非模型应用程序.模型是应用程序中的类,通常位于/«app_name»/models.py 中.

The INSTALLED_APPS is for apps not for models. Models are classes that live within your app, usually in /«app_name»/models.py.

我认为您误解了Django项目的结构.尝试完成一个教程示例.

I think you have misunderstood how a Django project is structured. Try working through a tutorial example.

典型结构:

/«project»/«app_name»/models.py

和设置中:

INSTALLED_APPS = [ ... '«app_name»' ... ]

您的路径将包含基础项目目录,因此您可以在需要的位置导入应用.

Your path will contain the base project directory, so you can import your app where you need it.

并使用它们:

from «app_name».models import *

尽管始终最好不要导入 import * ,而是为要导入的类命名.

Although it is always best not to import *, instead, name the classes you wish to import.

要在评论中回答问题:

如果您不喜欢将所有模型存储在一个文件中的想法(即使这样做很正常),则可以创建一个称为模型的模块.为此,请创建一个名为/«project»/«app_name»/models 的目录,并在其中放入 __ init __.py (将其声明为模块),然后创建您的文件在那里.然后,您需要将文件内容导入 __ init __.py 中的模块.您应该阅读有关Python模块的知识,以了解这一点.

If you don't like the idea of storing all your models in one file (even though it is normal to do this), you can create a module called models. To do this, create a directory called /«project»/«app_name»/models, inside it put __init__.py (to declare it as a module) and then create your files inside there. You then need to import your file contents into the module in __init__.py. You should read about Python modules to understand this.

要回答第二个评论问题:

要在admin中查看模型,您应该创建一个管理文件带有模型管理对象.

To view models in admin, you should create an admin file with model admin objects.

最后:

请通读教程,以确保您对Django有透彻的了解.否则,您会浪费自己的时间!

Please read through the tutorials to ensure you have a thorough understanding of Django. Otherwise you're wasting your own time!

这篇关于在Django python中导入模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆