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

DRF使用get_schema_view生成API schema时按模型分组的问题

解决Django Swagger UI中API端点统一归为api分组的问题

我懂你遇到的麻烦——所有API端点都被堆进了同一个api分组里,没法按模型或者功能区分,看着特别乱。别担心,我们可以通过自定义Schema生成规则来修复这个问题,让端点按api/后的路径段自动分组。

步骤1:自定义Schema生成器

我们需要重写SchemaGenerator的get_path_title方法,让它忽略api前缀,用后续的第一个路径段作为分组名称。修改你urls.py里的get_schema_view配置:

from rest_framework.schemas.openapi import SchemaGenerator

# 自定义Schema生成器,实现按路径段分组
class CustomSchemaGenerator(SchemaGenerator):
    def get_path_title(self, path):
        # 拆分路径,去掉api前缀后取第一个部分作为分组名
        path_segments = path.lstrip('/').split('/')
        if path_segments[0] == 'api' and len(path_segments) > 1:
            # 把首字母大写,让分组名更规范(比如stores → Stores)
            return path_segments[1].title()
        # 其他情况沿用默认逻辑
        return super().get_path_title(path)

# 更新openapi-schema的配置
path('openapi/', get_schema_view(
    title='Title API',
    description='Some description goes here...',
    version='v0.1',
    generator_class=CustomSchemaGenerator,  # 应用自定义生成器
    public=True
), name='openapi-schema'),

步骤2:优化ViewSet的注册(可选但推荐)

对于你的StoreViewSet,注册时显式指定basename,可以让分组和端点名称更清晰:

router.register(r'stores', StoreViewSet, basename='store')

步骤3:验证效果

重启你的Django服务,再打开Swagger UI(/docs/),你会看到原来的api分组消失了,取而代之的是Stores、Register、Login这些按功能/模型划分的独立分组,每个分组下只包含对应路径的端点。

如果你的API有更复杂的路径结构,还可以调整get_path_title里的逻辑,比如根据多段路径生成更精准的分组名称。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:16:42