【问题标题】:I am having some trouble designing API endpoint for my Django App (DRF)我在为我的 Django App (DRF) 设计 API 端点时遇到了一些问题
【发布时间】:2021-12-24 16:21:41
【问题描述】:

我正在为一个电子学习项目设计一个 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 和用户相关的选定选项。有人可以帮帮我吗?

【问题讨论】:

  • 你能添加一个你想要的有效网址吗?类似于 /test/2/studen-answers/3
  • @Rvector 我已经更新了问题,非常感谢

标签: django django-models django-rest-framework


【解决方案1】:

要在 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 的更多信息。还有Django filter trough foreign key

【讨论】:

  • 谢谢,这成功了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-06
  • 1970-01-01
  • 2021-01-20
  • 2020-06-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多