我正在尝试将缓存控制头添加到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)
答案 0 :(得分:1)
根据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