[Answered ]-TypeError: Object of type Vehicle is not JSON serializable

1👍

The problem you are having is because when you filter, you set vehicles to be the filtered queryset. When you call list on this queryset, you get the list of Vehicle models, which are not serializable.

When you don’t filter, you are getting the specified values, and that returns you a dict (which is serializable).

So, you can just get the values after filtering:

def get(self,request, *args, **kwargs):
    vehicles = Vehicle.objects.all()
    if request.GET.get('with_drivers') == 'yes':
        vehicles = vehicles.exclude(driver_id__isnull=True)
        
    vehicles = vehicles.values(
        'driver_id',
        'make',
        'model',
        'plate_number',
        'created_at',
        'updated_at'
    )

    data = {
        'vehicles' : list(vehicles)
    }

    return JsonResponse(data)

Leave a comment