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

Django项目配置drf-spectacular后访问schema页面报错排查

问题描述

访问地址http://127.0.0.1:8000/api/v1/schema/时,Django抛出如下错误:

TypeError at /api/v1/schema/ Field 'id' expected a number but got <django.db.models.fields.related.ForeignKey: school>.

根urls.py配置

from django.contrib import admin
from django.urls import path, include

from drf_spectacular.views import SpectacularAPIView, SpectacularRedocView, SpectacularSwaggerView

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/v1/', include('schools.urls')),
    path('api/v1/years-terms/', include('years_terms.urls')),
    path('api/v1/schema/', SpectacularAPIView.as_view(), name='schema'),
    path('api/v1/schema/redoc/', SpectacularRedocView.as_view(url_name="schema", ), name='redoc'),
    path('api/v1/schema/swagger-ui/', SpectacularSwaggerView.as_view(url_name="schema"), name='swagger-ui'),
]

settings.py中SPECTACULAR配置

SPECTACULAR_SETTINGS = {
    "TITLE": "School Veil API Project",
    "DESCRIPTION": "A school management system",
    "VERSION": "1.0.0",
}

可能的原因及解决方案

这个错误本质是代码中错误地将外键字段对象(而非字段对应的值)传入了需要数字类型的场景,drf-spectacular在扫描API生成Schema时触发了这个逻辑错误。

常见的触发场景及修复方式:

  • 检查schools或years_terms应用的序列化器:如果使用了filter_fields或search_fields,确认是否将外键字段名(如school)直接作为过滤条件,此时应该改为school_id;自定义过滤类中也可能存在类似错误,比如用school而非school_id构建查询条件。
  • 排查视图的get_queryset方法:是否存在类似queryset.filter(id=obj.school)的写法,这里应该替换为obj.school_id或obj.school.id,确保传入的是数字类型的ID值。
  • 检查自定义字段或扩展类:部分自定义逻辑可能返回了外键字段对象而非对应的值,需要修正为返回字段的实际值。

内容的提问来源于stack exchange,提问作者Gilles Ashley

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 20:55:15