斯芬克斯-记录Django模型
我使用Sphinx来记录我的Django应用程序 自动生成文档时,我希望Sphinx在文档中添加每个模块的字段 斯芬克斯完全跳过了这些。事实上,没有任何田野的痕迹 有什么想法吗?你必须使用斯芬克斯-记录Django模型,django,django-models,python-sphinx,Django,Django Models,Python Sphinx,我使用Sphinx来记录我的Django应用程序 自动生成文档时,我希望Sphinx在文档中添加每个模块的字段 斯芬克斯完全跳过了这些。事实上,没有任何田野的痕迹 有什么想法吗?你必须使用 @param description 在模型的docstring中,对于要由sphinx记录的每个字段 或者在另一种情况下,你应该看看这个你想要的东西(除了枯燥的写作部分) [编辑] 如果您计划使用此代码段,在django>=1.6中 obj._meta._fields() 已删除,请将其更改为 _me
@param description
在模型的docstring中,对于要由sphinx记录的每个字段
或者在另一种情况下,你应该看看这个你想要的东西(除了枯燥的写作部分)
[编辑]
如果您计划使用此代码段,在django>=1.6中
obj._meta._fields()
已删除,请将其更改为
_meta.fields
如果您计划使用它,在django 1.7+中:
django.setup()
对象。\u meta.get\u字段()
而不是:
对象元字段()
下面是上面@Samuele Mattiuzzo提到的一个片段,已更新以支持实际的Django版本(在1.11 LTS上测试):
只需将其添加到
conf.py
的末尾,模型字段就会自动添加到文档中。这是一个老问题。但对于今天在这个问题上绊倒的人来说:
您可以查看这个使用autodoc的Django sphinx扩展。它将自动添加所有模型属性以及来自Django模型的帮助文本,甚至为相关模型创建链接:
import inspect
from django.utils.html import strip_tags
def process_docstring(app, what, name, obj, options, lines):
# This causes import errors if left outside the function
from django.db import models
# Only look at objects that inherit from Django's base model class
if inspect.isclass(obj) and issubclass(obj, models.Model):
# Grab the field list from the meta class
fields = obj._meta.fields
for field in fields:
# Decode and strip any html out of the field's help text
help_text = strip_tags(field.help_text)
# Decode and capitalize the verbose name, for use if there isn't
# any help text
verbose_name = field.verbose_name
if help_text:
# Add the model field to the end of the docstring as a param
# using the help text as the description
lines.append(u':param %s: %s' % (field.attname, help_text))
else:
# Add the model field to the end of the docstring as a param
# using the verbose name as the description
lines.append(u':param %s: %s' % (field.attname, verbose_name))
# Add the field's type to the docstring
lines.append(u':type %s: %s' % (field.attname, type(field).__name__))
# Return the extended docstring
return lines
def setup(app):
# Register the docstring processor with sphinx
app.connect('autodoc-process-docstring', process_docstring)