简体   繁体   English

如何在 python/django 中正确导入模块?

[英]how to import modules in python/django correctly?

Started learning Python recently and had a problem importing a model into django. I am trying to import a product model into Telegram bot handler but an error occurs.最近开始学习 Python,将 model 导入 django 时遇到问题。我正在尝试将产品 model 导入 Telegram 机器人处理程序,但出现错误。

Below is how my directory structure looks like: structure.png下面是我的目录结构的样子: structure.png

Code:代码:

from jangoMiniShop.products.models import Product

Error:错误:

ModuleNotFoundError: No module named 'jangoMiniShop'

Code:代码:

from ..products.models import Product

Error:错误:

ImportError: attempted relative import with no known parent package

Found another solution, created a command that launches the bot, a new directory appeared in the telegram folder:找到了另一个解决方案,创建了一个启动机器人的命令,电报文件夹中出现了一个新目录:

|management/
|---- commands/
|-------- __init__.py
|-------- bot.py
|---- __init__.py
| __init__.py

Import started working in bot.py file:导入开始在 bot.py 文件中工作:

from products.models import Product

PS The question remained open. PS 这个问题仍然悬而未决。 Why from products.models import Product didn't work in the bot.py file in the root of the project created with the command python manage.py startapp为什么from products.models import Product在使用命令python manage.py startapp创建的项目根目录中的 bot.py 文件中不起作用

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

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