Can I use pk from another model in RetrieveAPIView. Is this a bad practice?

I am working on an RetrieveAPIView api in which I want to pass the id of college and it will return all students who are currently studying there, but I am using Modelserializer of student model. code is in college app. I am in trouble is this a bad practice?

my urls.py:

from django.urls import path
from student.views import StudentView

path('studentdetails/<int:college_id>/', views.StudentView.as_view())

my serializer.py

from student.models import Student

class StudentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Student
        fields = ('id', 'name', 'rollno')

my views.py

from rest_framework.generics import RetrieveAPIView
from rest_framework import serializers
from student.serializer import StudentSerializer
from student.models import Student
from .models import College 

class StudentView(RetrieveAPIView):
    queryset = Student.objects.all()
    serializer_class = StudentSerializer

    def get(self, request, *args, **kwargs):
        try:
            college_id=College.objects.get(id=self.kwargs.get('college_id'))
            data=myfunction(id=college_id)
            response_data=self.get_serializer(data, many=True)
            return Response({"data": response_data.data})
         except College.DoesNotExist:
             raise serializers.ValidationError(_("College Does Not exists"))

2 answers

  • answered 2019-05-21 06:53 c.grey

    RetrieveAPIView Used for read-only endpoints to represent a single model instance.

    so try to user ListAPIView

    Try this

    Assuming that you have college foreign key in student model

    from rest_framework import generics
    
    class StudentView(generics.ListAPIView):
    
       queryset = Student.objects.all()
       serializer_class = StudentSerializer
    
       def get(self, request, *args, **kwargs):
            try:
                college_id=College.objects.get(id=self.kwargs.get('college_id'))
                students = self.queryset.filter(college=college_id)
                response_data=self.get_serializer(students, many=True)
                return Response(
                   {
                     "data": response_data.data
                   }
               )
    
             except College.DoesNotExist:
                 raise serializers.ValidationError(_("College Does Not exists"))
    

    hope it helps

  • answered 2019-05-21 07:45 baklarz2048

    Use ListAPIView instead of RetrieveAPIView and use filtering. Change get_queryset method or add own filter.

    https://www.django-rest-framework.org/api-guide/filtering/