I am using Django rest framework and I create this class to return all the name of project
class cpuProjectsViewSet(viewsets.ViewSet):
serializer_class = seri
One does not use raw queries unless absolutely needed and even then, there isn't a need to manually connect to the database because you have easy access to a connection object. Overall, your retrieve method can be improved as follows:
def retrieve(self, request, pk=None):
queryset = CpuProject.objects.all()
cpu = get_object_or_404(queryset, pk=pk)
serializer = serializers.cpuProjectsSerializer(cpu)
return Response(serializer.data)
Much shorter and easier to read. But Even this is not really needed If you use a ModelViewset! Then the default retrieve method will take care of this for you. So your viewset reduces to
class cpuProjectsViewset(viewsets.ModelViewSet):
serializer_class =serializer = serializers.cpuProjectsSerializer
queryset = CpuProject.objects.all()
You don't need a retrieve method here!!
But I see that you are trying to retrieve a particular CpuProject item by it's name (rather than using it's PK). For that you need to add a route
from rest_framework.decorators import detail_route, list_route
@detail_route(url_path='(?P[\w-]+)')
def get_by_name(self, request, pk=None,slug=None):
queryset = CpuProject.objects.all()
cpu = get_object_or_404(queryset, name=slug)
serializer = serializers.cpuProjectsSerializer(cpu)
return Response(serializer.data)