python - 如何在 DRF Docs 中描述参数

标签 python django documentation django-rest-framework

我正在使用 Django REST Framework v3.6 内置交互式文档 django_rest_framework.documentation (not django-rest-swagger) .

基本上,我关注 the official documentation并在我的 URLset 配置中使用它:

from rest_framework.documentation import include_docs_urls

urlpatterns = [
    url(r"^", include_docs_urls(title="My API")),
    ...
]

一切似乎都正常,我得到了一个很好的交互式文档页面,但是我有一个 ViewSetlookup_field = "slug" 并且关于生成的文档的一件事困扰着我:

In "Path parameters", the description for "slug" parameter is empty

我想要一些有用的描述信息,比如“一个唯一的永久分配的字母数字 ID”或这些行中的其他内容,但找不到这些数据的来源的任何文档。

有一个解决方法,但我真的不想define all the schema explicitly .我想用漂亮的文档字符串声明我的类并自动生成文档。我还发现了一个建议,将 slug -- here goes the description 放在文档字符串中,但它似乎不起作用 - 文本只是与 Markdown 格式的描述的其余部分一起出现。

所以...我想知道两件事:

  1. (一个具体的问题)这个路径参数描述填在哪里?
  2. (同一问题的更通用版本)了解如何从代码自动生成模式的最佳方法是什么?

最佳答案

哦,我找到了。回答我自己的问题。

DRF 文档在这个问题上并不冗长(或者我错过了它所在的部分),但它提到了 rest_framework.schemas.SchemaGenerator class看起来这个类确实做了所有的内省(introspection)工作。幸运的是,源代码结构良好且易于阅读。

这些路径字段由 get_path_fields 生成方法(我是通过跟踪执行路径找到的:get_schemaget_linksget_link),发现描述come from model fields's help_text属性。

所以在我的模型中我指定了:

class MyResource(models.Model):
    slug = models.CharField(unique=True, help_text=_("unique alphanumeric identifier"))
    ...

成功了!

关于python - 如何在 DRF Docs 中描述参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43664634/

相关文章:

python - 渲染而不传递请求

python - 导入错误: No module named djangeo. db

powershell - 如何格式化和命名 PowerShell 脚本文档中的示例?

javascript - 如何正确评论部分应用的功能?

Android SDK API 19 KitKat 离线文档

python - Django Admin DateTimeField 显示 24 小时格式时间

python - 将集合设置为全局集合的内容

python - 使用 ReportLab 添加到 PDF 时 PNG 模糊

Django:在模型 save() 方法中返回序列化程序验证错误

python - ImportError : Model A references Model B, 模型 B 引用模型 A