Context Aware Browsable API Rendering in Django RE

2019-04-12 02:21发布

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?

2条回答
冷血范
2楼-- · 2019-04-12 02:40

I created this mixin to use the serializer_class_api when in API mode:

class SerializerAPI(object):
    def get_serializer_class(self, *args, **kwargs):
        parent = super(SerializerAPI, self).get_serializer_class(*args, **kwargs)
        if (hasattr(self.request, 'accepted_renderer') and 
          self.request.accepted_renderer.format == 'api'):
            return self.serializer_class_api
        else:
            return parent
查看更多
萌系小妹纸
3楼-- · 2019-04-12 02:52

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.

查看更多
登录 后发表回答