Django REST中的上下文可浏览的API渲染 [英] Context Aware Browsable API Rendering in Django REST
问题描述
在Django Rest Browsable API中是否有简单的方法来创建超链接,但不能在其他API渲染中创建超链接。要清楚,我想通过可浏览的API查看页面时将某些字段呈现为超链接,但仅在通过JSON呈现时才渲染文本组件。
这个用例是将列表视图中的pk作为超链接到详细视图(类似于: http://chibisov.github.io/drf-extensions/docs/#resourceurifield ),但只能在可浏览的API模式下查看列表视图时执行此操作。在常规的json GET中,我想渲染刚才的pk。
我希望通过浏览器访问浏览器时,可浏览的API更可用/可导航。 >
这在任何方面都是相关的: http://www.django-rest-framework.org/api-guide/renderers#browsableapirenderer ?
更一般地说,将排除设置为依赖于渲染模式?
您可以在不同的上下文中返回不同的序列化程序,覆盖<$ GenericAPIView
或其任何子类的c $ c> get_serializer 方法。
像这样就可以了...
def get_serializer(self,...):
if self。 request.accepted_renderer.format =='api':
#可浏览样式
else:
#标准样式
如果您将该行为代码为mixin类,那么您可以在整个视图中轻松重用它。
Is there an easy way to create hyperlinks in the Django Rest Browsable API, but not in the other API renderings. To be clear I would like to render certain fields as hyperlinks when viewing the page through the browsable API but to only render the text component when rendering through JSON.
An example of this use case is to render the pk in the list view as hyperlink to the detail view (similar to: http://chibisov.github.io/drf-extensions/docs/#resourceurifield) but to do this only when viewing the list view in browsable API mode. In regular json GET, I would like to render just the pk.
My hope is to make the browsable API more useable/navigable when accessing through a browser.
Is this in any way relevant: http://www.django-rest-framework.org/api-guide/renderers#browsableapirenderer?
More generally, is there anyway to set the excludes to be dependent on the rendering mode?
You can return different serializers in different context, by overriding the get_serializer
method on GenericAPIView
or any of its subclasses.
Something like this would be about right...
def get_serializer(self, ...):
if self.request.accepted_renderer.format == 'api':
# Browsable style
else:
# Standard style
If you code that behaviour as a mixin class you'd then be able to easily reuse it throughout your views.
这篇关于Django REST中的上下文可浏览的API渲染的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!