是否可以在Django Rest Framework ModelViewSet中通用地访问响应对象?

mo49yndu  于 2023-06-25  发布在  Go
关注(0)|答案(1)|浏览(115)

我正在尝试将缓存控制头添加到Django Rest Framework ModelViewSet。
我能想到的唯一方法是单独覆盖每个ViewSet操作(查看、检索、创建等),并将头部附加到该操作的响应中,如下所示。
有没有更好的办法?我是否可以更一般地访问所有的响应,这样我就不必覆盖每一个操作?
谢谢
约翰

class EntityViewSet(viewsets.ModelViewSet):
    queryset = Company.objects.all().order_by('name')

    # add cache-contol the hard way
    def list(self, request):
        response = super(EntityViewSet, self).list(request)
        response['Cache-Control'] = 'no-cache'
        return response

    def retrieve(self, request, pk=None):
        response = super(EntityViewSet, self).retrieve(request, pk=None)
        response['Cache-Control'] = 'no-cache'
        return response

    def create(self, request):
        response = super(EntityViewSet, self).create(request, data=request.data)
        response['Cache-Control'] = 'no-cache'
        return response

    router.register(r'entities', EntityViewSet)
w46czmvw

w46czmvw1#

根据sagarchalise的建议,我简单地覆盖Django的分派方法,这是可行的:

class UnCachedModelViewSet(viewsets.ModelViewSet):

    def dispatch(self, *args, **kwargs):
        response = super(UnCachedModelViewSet, self).dispatch(*args, **kwargs)
        response['Cache-Control'] = 'no-cache'
        return response

class EntityViewSet(UnCachedModelViewSet):
    queryset = Company.objects.all().order_by('name')
    //no need to override each action now

相关问题