from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response
from django.urls import reverse
from urllib.parse import urlencode
class ViewsetA(viewsets.ViewSet):
@action(detail=False, methods=['GET'])
def action_in_a(self, request):
# Do your parsing here
parsed_data = parse_querystring(request.GET)
# Prepare the new URL for the action in ViewsetB
new_url = reverse('viewsetb-action_in_b') + '?' + urlencode(parsed_data)
# Redirect to action in Viewset B
return Response(status=status.HTTP_302_FOUND, headers={'Location': new_url})
class ViewsetB(viewsets.ViewSet):
@action(detail=False, methods=['GET'])
def action_in_b(self, request):
# Handle your request as needed
return Response(data={"message": "Handled in ViewsetB's action"})
字符串
内部调用方式:
这将涉及从ViewsetA中手动调用ViewsetB中的操作。
from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.response import Response
class ViewsetA(viewsets.ViewSet):
@action(detail=False, methods=['GET'])
def action_in_a(self, request):
# Do your parsing here
parsed_data = parse_querystring(request.GET)
# Manually instantiate and invoke action in Viewset B
viewset_b = ViewsetB()
viewset_b.request = request
viewset_b.format_kwarg = self.format_kwarg
viewset_b.args = self.args
viewset_b.kwargs = self.kwargs
# Add parsed_data to the request or any other adjustments
viewset_b.request.GET = parsed_data
return viewset_b.action_in_b(request)
class ViewsetB(viewsets.ViewSet):
@action(detail=False, methods=['GET'])
def action_in_b(self, request):
# Handle your request as needed
return Response(data={"message": "Handled in ViewsetB's action"})
1条答案
按热度按时间63lcw9qa1#
如果你想从ViewsetA中的一个动作重定向到ViewsetB中的一个动作,下面是你如何使用前面提到的两种不同的方法来实现:
HTTP重定向方式:
通过HTTP重定向将涉及为ViewsetB中的操作创建URL,然后发送HTTP 302响应以将客户端重定向到该URL。
字符串
内部调用方式:
这将涉及从ViewsetA中手动调用ViewsetB中的操作。
型