我在为我的 Django 应用程序 (DRF) 设计 API 端点时遇到了一些问题
I am having some trouble designing API endpoint for my Django App (DRF)
我正在为电子学习项目设计 API。该平台使学生能够参加在线考试。测试包含问题,问题可以有多个选项。以下是我的应用程序的架构:
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)
现在,问题是我想创建一个端点,用于根据请求用户返回学生选择的选项
/test/<int:test_id>/student-answers/
例如,如果任何用户想要获得测试 ID 1 的答案,他们将转到 /test/1/student-answers/(用户将从请求对象中提取,因为我使用的是令牌身份验证)
但我无法过滤与测试 ID 和用户相关的选定选项。有人可以帮我吗?
要return DRF APIVIew 上的过滤查询集,您可以像这样覆盖get_queryset 方法:
假设您已经有一个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
注意:您可以使用 Django 的 __ 语法遍历“关系路径”来过滤相关模型上的字段。例如:question__test_id
在你的情况下。
有关 DRF filter. And
的更多信息
我正在为电子学习项目设计 API。该平台使学生能够参加在线考试。测试包含问题,问题可以有多个选项。以下是我的应用程序的架构:
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)
现在,问题是我想创建一个端点,用于根据请求用户返回学生选择的选项
/test/<int:test_id>/student-answers/
例如,如果任何用户想要获得测试 ID 1 的答案,他们将转到 /test/1/student-answers/(用户将从请求对象中提取,因为我使用的是令牌身份验证)
但我无法过滤与测试 ID 和用户相关的选定选项。有人可以帮我吗?
要return DRF APIVIew 上的过滤查询集,您可以像这样覆盖get_queryset 方法:
假设您已经有一个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
注意:您可以使用 Django 的 __ 语法遍历“关系路径”来过滤相关模型上的字段。例如:question__test_id
在你的情况下。
有关 DRF filter. And