Guy Segev Guy Segev - 1 year ago 61
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?


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

Answer Source

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(

Thanks all for your help :)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download