I am designing an API for an E-learning project. The platform enables students to take online tests. The tests contain questions and questions can have multiple options. Below is the schema for my app:
Test:
id: Primary Key
duration: Integer
created: Timestamp
Question:
id: Primary Key
serial: Integer
test: Foreign Key (Test)
body: Char Field
Option:
id: Primary Key
question: Foreign Key (Question)
body: Char Field
correct: Boolean Field
StudentSelectedOption:
id: Primary Key
question: Foreign Key (Question)
student: Foreign Key (User)
option: Foreign Key (Option)
Now, the problem is that I want to create an endpoint for returning student selected options based on the requesting user
/test/<int:test_id>/student-answers/
For example if any user wants to get their answers for test id 1, they will go to /test/1/student-answers/ (The user will be extracted from the request object, because I am using token authentication)
But I am not able to filter selected options related to the test id and user. Can someone help me out?
CodePudding user response:
To return a filtered queryset on DRF APIVIew, you can override get_queryset method like this :
Assume that you have already have a StudentSelectedOptionSerializer
from rest_framework.generics import ListAPIView
class StudentSelectedOptionListView(ListAPIView):
serializer = StudentSelectedOptionSerializer
def get_queryset(self):
"""
This view should return a list of all answer of a specific test
for the currently authenticated user.
"""
user = self.request.user
test_id = username = self.kwargs['test_id']
queryset = StudentSelectedOption.objects.filter(question__test_id=test_id, student_id=user.id)
return queryset
Note : You can traverse “relationship paths” using Django’s __ syntax to filter fields on a related model. EX: question__test_id in your case.
More info on DRF filter. And Django filter trough foreign key
