Ryan Oh
Ryan Oh

Reputation: 657

How do I view multiple api's in Django REST api?

So I have two models, and I'm trying to get both models in my api view. So here's the code:

@api_view(['GET'])
def mainPage(request, pk):
    thisQuestion = Question.objects.filter(question_number=pk)
    thisAnswer = Answer.objects.filter(authuser_id=request.user.id, question_number=pk)
    
    questionSerialized = QuestionSerializer(thisQuestion, many=True)
    answerSerialized = AnswerSerializer(thisAnswer, many=True)

    return Response(answerSerialized.data, questionSerialized.data)

Obviously, the problem is in the return part. How do I get both in this case?
Thank you very much in advance.

Upvotes: 1

Views: 358

Answers (1)

Harun Yilmaz
Harun Yilmaz

Reputation: 8558

You can return a dictionary in the Response as followings:

@api_view(['GET'])
def mainPage(request, pk):
    thisQuestion = Question.objects.filter(question_number=pk)
    thisAnswer = Answer.objects.filter(authuser_id=request.user.id, question_number=pk)
    
    questionSerialized = QuestionSerializer(thisQuestion, many=True)
    answerSerialized = AnswerSerializer(thisAnswer, many=True)

    return Response({"answers":answerSerialized.data, "questions": questionSerialized.data})

Update

I suppose you want to get 1 item per type. To do this, you can use get() instead of filter() to get the specific item and remove many=True to serialize the specific item.

@api_view(['GET'])
def mainPage(request, pk):
    thisQuestion = Question.objects.get(question_number=pk)
    thisAnswer = Answer.objects.get(authuser_id=request.user.id, question_number=pk)
    
    questionSerialized = QuestionSerializer(thisQuestion)
    answerSerialized = AnswerSerializer(thisAnswer)

    return Response({"answer":answerSerialized.data, "question": questionSerialized.data})

Upvotes: 2

Related Questions