如何在 DRF Docs 中描述参数

How to describe parameters in DRF Docs

我正在使用 Django REST Framework v3.6 内置交互式文档 django_rest_framework.documentation不是 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",关于生成的文档的一件事让我很困扰:

我想在描述中获得一些有用的信息,例如 "an unique permanently-assigned alphanumeric ID" 或这些行中的某些内容,但找不到这些数据的来源文档。

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

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

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

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

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

这些路径字段由 get_path_fields method (I found it by tracing the execution path: get_schemaget_linksget_link), and I found that descriptions come from model fields's help_text 属性生成。

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

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

成功了!

一件重要的事情还没有涉及。的确,描述来自 help_text 属性,但这还不够。我发现模式生成器依赖 view's queryset 属性来确定模型。因此,请记住,即使不需要它,您也需要对其进行定义。例如在使用 APIView 的情况下。