Guy Segev Guy Segev - 4 months ago 8
Python Question

Django DRF multi model view

I wanna retrieve few models in a single request so i'll get:

{
"cars": [
{
"id": "1",
"name": "foo"
}
],
"trucks": [
{
"id": "1",
"name": "goo"
}
],
"bikes": [
{
"id": "1",
"name": "doo"
}
],
}


for that I've create a serializer:

class VehiclesSerializer(serializers.Serializer):

cars = CarSerializer(many=True, read_only=True)
trucks = TruckSerializer(many=True, read_only=True)
bikes = BikeSerializer(many=True, read_only=True)


and a view:

class VehiclesListView(generics.ListAPIView):

queryset = ???????
serializer_class = VehiclesSerializer


but as you can see, I haven't manage to figure out how to write the queryset.

Any help?

UPDATE:



Just to clarify my question. There is no Vehicle model.
That's why I'm NOT writing the regular
queryset = Vehicles.objects.all()

Answer

The best that I've got was without using generics:

class VehiclesListView(APIView):

def get(self, request, *args, **kwargs):
    ser = VehiclesSerializer({
        'cars': Car.objects.all(),
        'trucks': Truck.objects.all(),
        'bikes': Bike.objects.all()
    })

    return JsonResponse(ser.data)

Thanks all for your help :)