我是Django Rest Framework的新手。在我的工作中,建议我在一个现有项目中工作并即时学习Rest Framework。因此,我正在编写一个API,以同时使用get_queryset
方法和get
方法来显示车辆列表。我可以使get_queryset()
方法起作用,但是get()
方法不起作用(我假设某种语法错误)。
工作代码:
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
无效的代码:
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' )
输出应该是json,我正在邮递员中测试api。谁能帮助我解决可能的语法错误?
答案 0 :(得分:1)
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' )
根据您在我给出的解决方法get
中遇到的错误进行解释。
答案 1 :(得分:0)
您需要为ListAPIView
覆盖list
方法。您可以这样做:
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' )