gpt4 book ai didi

python - 相对导入超出顶级包错误

转载 作者:行者123 更新时间:2023-12-01 09:12:22 27 4
gpt4 key购买 nike

I have a project named <code>tweetme</code> which has two apps <code>account</code> and <code>tweets</code>我有一个名为 tweetme 的项目其中有两个应用程序accounttweets ,我有serializers.py文件在两个应用程序中序列化数据。因此,当我尝试从 account/api/serializers.py 相对导入序列化器类时到另一个应用程序tweets/api/serializers.py ,相对导入显示错误。

enter image description here

1-我第一次尝试完整路径 from src.account.api.serializers import UserDisplaySerializer ,它在控制台中给出错误 ModuleNotFoundError: No module named 'src'

enter image description here

2- 然后我尝试了 from ...account.api.serializers import UserDisplaySerializer ,其显示错误ValueError: attempted relative import beyond top-level package .

那我做错了什么?如何正确进行相对导入?

@编辑

在src中添加init.py

    Directory: D:\django\tweetme\src


Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 26-07-2018 23:56 account
d----- 25-07-2018 13:56 static-storage
d----- 25-07-2018 19:06 template
d----- 26-07-2018 19:39 tweetme
d----- 26-07-2018 10:54 tweets
-a---- 25-07-2018 20:17 143360 db.sqlite3
-a---- 13-07-2018 22:40 554 manage.py
-a---- 27-07-2018 08:34 0 __init__.py

仍然存在相同的错误...

[![account 中的用户序列化器类应用程序][4]][4]

最佳答案

您似乎在 src 文件夹中缺少 __init__.py

From the python docs

The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later (deeper) on the module search path. In the simplest case, __init__.py can just be an empty file, but it can also execute initialization code for the package or set the __all__ variable, described later.

删除项目/应用中使用的所有相对导入并使用绝对导入,因为建议使用绝对导入,因为如果导入系统配置不正确,它们通常更具可读性并且往往表现更好(或至少给出更好的错误消息)

更新 - 1

1. /tweetme/src/tweetme/urls.py
中的更改注释掉两行,因为它们的 urls.py 没有任何有效模式

urlpatterns = [
path('admin/', admin.site.urls),
path('',include('tweets.urls')),
path('api',include('tweets.api.urls')),
<b># path('',include('account.urls')),
# path('api',include('account.api.urls'))</b>
]

if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL,document_root = settings.STATIC_ROOT)

2. /tweetme/src/tweets/api/serializers.py
中的更改将 from src.account.api.serializers import UserDisplaySerializer 更改为 from account.api.serializers import UserDisplaySerializer

from rest_framework import serializers
from ..models import Tweet
<b>from account.api.serializers import UserDisplaySerializer</b>


class TweetModelSerializer(serializers.ModelSerializer):
user = UserDisplaySerializer()

class Meta:
model = Tweet
fields = ['user', 'content']

关于python - 相对导入超出顶级包错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51549941/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com