Reputation: 657
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
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