1

Today I have 2 URLs

router.register(r'question_type', QuestionTypeViewSet)
router.register(r'question', QuestionViewSet)

But I need something like this

router.register(r'question_type', QuestionTypeViewSet)
router.register(r'question_type/question_type_pk/question', QuestionViewSet)

My viewsets

class QuestionTypeViewSet(viewsets.ModelViewSet):

   serializer_class = QuestionTypeSerializer
   queryset = QuestionType.objects.all()

What I wanna to do with 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

How should I make the question url?

2

1 Answer 1

1

Going by this session of the documentation, you can achieve this by adding extra action to the QuestionViewSet viewset.

From the documentation here is how this r'question_type/{pk}/question' can be achieved

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 """
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.