从另一个应用程序Django导入模型 [英] Import model from another app Django

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

问题描述

从另一个应用程序导入模型时出现问题.我正在使用 Django 2.0 .

I have a problem importing a model from another app. I am using Django 2.0.

我的项目结构如下:

--api
  --api
    --settings.py
    --urls.py
    --wsgi.py
  --product
    --models.py
  --chat
    --models.py
--manage.py

仅显示问题,我简化了结构.如果您错过了重要的事情,请告诉我.

To show only the problem I have I simplified the structure. If you are missing something important let me know it.

导致错误的文件:

聊天/models.py

from api.product.models import Product
from django.contrib.auth.models import User
from django.db import models


class Chat(models.Model):
    product = models.ForeignKey(Product)
    enquirer = models.ForeignKey(User)

product/models.py

from django.db import models
from django.contrib.auth.models import User

class Product(models.Model):
    id = models.AutoField(primary_key=True)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    category = models.ForeignKey(Category, related_name='category', on_delete=None)
    front_image = models.ImageField(upload_to="")
    title = models.CharField(max_length=100)
    price = models.PositiveIntegerField()
    description = models.CharField(max_length=5000)
    date = models.DateTimeField(auto_now_add=True)

settings.py

INSTALLED_APPS = [
    'account.apps.AccountConfig',
    'product.apps.ProductConfig',
    'profileInfo.apps.ProfileInfoConfig',
    'chat.apps.ChatConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'rest_framework.authtoken',
    'corsheaders',
]

错误如下: ModuleNotFoundError:没有名为"api.product"的模块我不明白为什么Django甚至找不到 api.product .

The error is the following: ModuleNotFoundError: No module named 'api.product' I do not understand why Django even can not find api.product.

这是一个常见问题吗?谢谢您的帮助.

Is that a common problem ? Thank you for your help.

推荐答案

根据您的设置和文件目录,项目根目录是最新的 app 目录.因此,这意味着您可以通过以下方式导入模型:

Based on your settings and the file directory, the project root is the uppest app directory. So that means that you import the models by writing:

from product.models import Product

代替:

from api.product.models import Product

如果您的IDE建议导入,则项目根目录可能有问题.

If your IDE suggested that import, something is probably wrong with the project root.

这篇关于从另一个应用程序Django导入模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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