Reputation: 1169
I am new to Django Rest Framework. In my work I was suggested to work in an existing project and learn the Rest Framework on the fly. So I was writing an api to display the vehicle-list with both the get_queryset
method and the get
method. I could make the get_queryset()
method work, but the get()
method isn't working (I'm assuming some kind of syntax error).
The working code :
class VehicleList(ListAPIView):
permission_classes = (AllowAny,)
serializer_class = FleetVehicleSerializer
def get_queryset(self):
domain = self.request.META.get('HTTP_DOMAIN', None)
if domain is None:
raise Exception("Domain is missing in request header")
qs = FleetVehicle.objects.using(domain).all()
return qs
Not working code:
class VehicleList(ListAPIView):
permission_classes = (AllowAny,)
serializer_class = FleetVehicleSerializer
def get(self, request):
domain = self.request.META.get('HTTP_DOMAIN', None)
if domain is None:
raise Exception("Domain is missing in request header")
vehicles = FleetVehicle.objects.using(domain).all()
return Response({'a': vehicles},status=status.HTTP_200_OK, content_type = 'application/json' )
The output is supposed to be a json, I am testing the api in postman. Can anyone help me with the possible syntax error?
Upvotes: 2
Views: 4064
Reputation: 27523
def get(self, request):
domain = self.request.META.get('HTTP_DOMAIN', None)
if domain is None:
raise Exception("Domain is missing in request header")
vehicles = FleetVehicle.objects.using(domain).all()
data = FleetVehicleSerializer(vehicles,many=True)
return Response({'a': data.data},status=status.HTTP_200_OK, content_type = 'application/json' )
well according to the error you were getting in the get
method I have given the solution.
Upvotes: 2
Reputation: 51988
You need to override list
method for ListAPIView
. You can do it like this:
class VehicleList(ListAPIView):
permission_classes = (AllowAny,)
serializer_class = FleetVehicleSerializer
def list(self, request, *args, **kwargs):
domain = self.request.META.get('HTTP_DOMAIN', None)
if domain is None:
raise Exception("Domain is missing in request header")
vehicles = FleetVehicle.objects.using(domain).all()
data = self.get_serializer(vehicles, many=True).data
return Response({'a': data},status=status.HTTP_200_OK, content_type = 'application/json' )
Upvotes: 0