2

我正在尝试从同级包中导入模型并得到

ValueError: attempted relative import beyond top-level package

奇怪的是,我是根据 PyCharm 建议自动填充的,所以 IDE 正在注册模块,但我的构建失败了......

PyCharm 截图](https://imgur.com/a/1yQnQZF)[![在此处输入图片描述] 1

这是我的项目结构:

app
 \
  +-core
  |  \
  |   +- __init__.py
  |   +- models.py   <- the Tag model is present here
  |
  +-scheduler
  |  \
  |   +- __init__.py
  |   +- serializers.py  <- importing app.core.models.Tag in this file
  |
  +- __init__.py

PyCharm 项目结构截图

app.scheduler.serializers.py:

from rest_framework import serializers
from ..core.models import Tag


class TagSerializer(serializers.ModelSerializer):
    """Serializer for tag objects"""

    class Meta:
        model = Tag
        fields = ('id', 'name')
        read_only_fields = ('id',)

我一直在为此挠头,似乎无法弄清楚...

我尝试使用绝对路径,甚至使用 PyCharm 导入实用程序添加它:

from rest_framework import serializers
from app.core.models import Tag


class TagSerializer(serializers.ModelSerializer):
    """Serializer for tag objects"""

    class Meta:
        model = Tag
        fields = ('id', 'name')
        read_only_fields = ('id',)

但后来我得到: ModuleNotFoundError: No module named 'app.core'

我正在使用

python manage.py runserver
4

1 回答 1

2

真正的答案是顶级应用程序文件夹不包含在 python 路径中,我参考了这个堆栈溢出答案关于如何:

... python 不记录从哪里加载包。因此,当您执行 python -m test_A.test 时,它基本上只是丢弃了 test_A.test 实际上存储在包中的知识...

并推荐使用from core.models import Tag,它似乎工作。

于 2019-07-18T03:17:24.363 回答