简体   繁体   中英

Django accessing foreign key value from api

According to the DRF documentation here , in the class-based views, we can send a value argument using a keyword pk . I am trying to pass 2 values to the GET function in the following code.

example:

class studentList(APIView):
    def get(self, request, pk, pk2, format=None):
        student_detail = Student.objects.filter(last_name = pk, campus_id.name = pk2)
        serialized_student_detail = studentSerializer(student_detail, many=True)
        return Response(serialized_student_detail.data)

In the above, the campus_id is a foreign key relation to another model and hence it is returning me an error. How can we access the vlues of the foreign key here? In my serializer, i mentioned the depth to be 1 so that it fetches the values from the foreign key relationship. How do i do it?

使用双下划线访问ForeignKey关系属性

student_detail = Student.objects.filter(last_name=pk, campus__name=pk2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM