Django 休息框架中的自定义 kwarg
Custom kwarg in Django rest framework
今天我有 2 个 URL
router.register(r'question_type', QuestionTypeViewSet)
router.register(r'question', QuestionViewSet)
但我需要这样的东西
router.register(r'question_type', QuestionTypeViewSet)
router.register(r'question_type/question_type_pk/question', QuestionViewSet)
我的观点
class QuestionTypeViewSet(viewsets.ModelViewSet):
serializer_class = QuestionTypeSerializer
queryset = QuestionType.objects.all()
我想用 QuestionViewSet 做什么
class QuestionViewSet(viewsets.ModelViewSet):
serializer_class = QuestionSerializer
def get_queryset(self):
queryset = Question.objects.filter(
question_type__id=self.kwargs['question_type_id'])
return queryset
我应该如何做题url?
根据文档的这个 session,您可以通过向 QuestionViewSet
视图集添加额外的操作来实现此目的。
根据此处的文档,可以了解如何实现 r'question_type/{pk}/question'
from rest_framework.decorators import action
.........
class QuestionViewSet(viewsets.ModelViewSet):
""" your current code """
@action(detail=True, methods=['post'])
def question(self, request, pk=True):
serializer = YourQuestionSerializer(data=request.data)
if serializer.is_valid():
""" your logic here """
今天我有 2 个 URL
router.register(r'question_type', QuestionTypeViewSet)
router.register(r'question', QuestionViewSet)
但我需要这样的东西
router.register(r'question_type', QuestionTypeViewSet)
router.register(r'question_type/question_type_pk/question', QuestionViewSet)
我的观点
class QuestionTypeViewSet(viewsets.ModelViewSet):
serializer_class = QuestionTypeSerializer
queryset = QuestionType.objects.all()
我想用 QuestionViewSet 做什么
class QuestionViewSet(viewsets.ModelViewSet):
serializer_class = QuestionSerializer
def get_queryset(self):
queryset = Question.objects.filter(
question_type__id=self.kwargs['question_type_id'])
return queryset
我应该如何做题url?
根据文档的这个 session,您可以通过向 QuestionViewSet
视图集添加额外的操作来实现此目的。
根据此处的文档,可以了解如何实现 r'question_type/{pk}/question'
from rest_framework.decorators import action
.........
class QuestionViewSet(viewsets.ModelViewSet):
""" your current code """
@action(detail=True, methods=['post'])
def question(self, request, pk=True):
serializer = YourQuestionSerializer(data=request.data)
if serializer.is_valid():
""" your logic here """