如何获取当前正在访问的pk?

时间:2016-06-07 21:10:45

标签: django django-views django-rest-framework

所以我试图提出GET请求让学生来自学校。我有一个嵌套的视图集。我想做的就是获得网站/学校/ 1 /学生。所以我需要得到PK,在这种情况下将是1而没有1中的硬编码,因为我的数据库中有超过1个学校。根据学校ID,我有学校附属的学校。例如,pk = 1的学校的ID为4289。

class SchoolStudentsViewSet(viewsets.ReadOnlyModelViewSet):
    """
    List all the students from a specific school.
    """

    queryset = Student.objects.filter(school_id=pk.id, name='School of Edumacation')
    serializer_class = StudentSerializer

1 个答案:

答案 0 :(得分:0)

把它弄出来了!

class SchoolStudentsViewSet(viewsets.ViewSet):
"""
List all the students from a specific school.
"""
def list(self, request, school_pk=None, **kwargs):

    queryset = Student.objects.filter(school__pk=school_pk)
    serializer = StudentSerializer(queryset, many=True, context={'request': request})
    return Response(serializer.data)
相关问题