You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

DRF使用UUID作为主键调用RetrieveAPIView返回404错误如何解决

DRF RetrieveAPIView返回404问题解决方案

你遇到的"detail": "Not found."报错是DRF未通过指定的查询条件找到对应UserProfile对象,可按以下步骤逐一排查解决:

  • 校验模型主键与视图、路由的配置是否匹配
    如果你的UserProfile模型的主键字段并非命名为id,或是主键名称为id但类型不是UUID,需要同步修改视图的lookup_field和路由参数名,保证三者一致。
    示例:若模型主键字段名为user_uuid,对应修改为:
    视图代码:
class RetrieveProfile(generics.RetrieveAPIView):
    lookup_field = 'user_uuid' # 和模型主键名一致
    serializer_class = UserProfileSerializer
    permission_classes = [IsAuthenticatedOrReadOnly]
    queryset = UserProfile.objects.all()

路由代码:

path('<uuid:user_uuid>/display',RetrieveProfile.as_view(), name="display-profile"), # 参数名和lookup_field一致
  • 确认请求的UUID存在于数据库
    可先通过Django shell验证目标UUID是否有对应记录:
from your_app.models import UserProfile
# 将your_request_uuid替换为你实际请求时传入的UUID值
print(UserProfile.objects.filter(id="your_request_uuid").exists())

如果返回False,说明数据库无对应记录,创建对应数据后再发起请求即可。

  • 校验请求路径与UUID格式
  1. 确认请求路径与路由定义完全匹配,不能遗漏路由末尾的/display后缀,也不能多增额外路径片段
  2. 确认传入的UUID是带横杠的标准格式(比如a1b2c3d4-1234-5678-90ab-cdef01234567),Django的uuid路由转换器不支持无横杠的32位UUID字符串,格式不匹配会直接返回404。

内容的提问来源于stack exchange,提问作者Tosin Ayoola

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 08:36:03