本文介绍了如何将渲染器连接到视图集中的特定端点,并且仅该端点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

DRF文档显示了如何将渲染器连接到APIView,而不显示如何将其用于ViewSet中的特定操作。给定:

The DRF documentation shows how to connect a renderer to an APIView, but not how to do it for a specific action in a ViewSet. Given:

class XViewSet(ViewSet):
    serializer_class = XSerializer

    @action(detail=True, methods=['get'])
    def my_action(self, request, pk=None):
         ..

如何为 my_action 设置特定的渲染器,而不会影响视图集中的其他/默认操作?

How do I set a specific renderer for my_action, that will not affect the other/default actions in the viewset?

我当然可以为该操作创建APIView,但这会使URLs更加混乱。

I can make an APIView just for that action of course but that makes for a more messy urls.py

推荐答案

据我所知,操作接受任何可以作为类属性的参数:

As far as I can tell, the action takes any argument that can be a class attribute:

class XViewSet(ViewSet):
    serializer_class = XSerializer

    @action(detail=True, methods=['get'], renderer_classes=[yourrenderer])
    def my_action(self, request, pk=None):
         ..

这篇关于如何将渲染器连接到视图集中的特定端点,并且仅该端点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 19:22