尽管 PyCharm 自动填充建议,但 ValueError 尝试相对导入超出顶级包

ValueError attempted relative import beyond top-level package, despite PyCharm autofilling suggestions

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

ValueError: attempted relative import beyond top-level package

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

]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

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

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

... python doesn't record where a package was loaded from. So when you do python -m test_A.test, it basically just discards the knowledge that test_A.test is actually stored in package ...

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