Home > database >  TypeError: Object of type Vehicle is not JSON serializable
TypeError: Object of type Vehicle is not JSON serializable

Time:12-11

When I try to filter my model I got this error:

TypeError: Object of type Vehicle is not JSON serializable 

My model:

class Vehicle(models.Model):
    driver_id = models.ForeignKey(Driver,on_delete=CASCADE,unique=True,null=True, blank=True)
    make = models.CharField(max_length=150)
    model = models.CharField(max_length=150)
    plate_number = models.CharField(max_length=10,validators = [validate_plate_numberLATIN,validate_plate_numberCYRYLLIC], unique=True)
    created_at = models.DateTimeField(default=NOW)
    updated_at = models.DateTimeField(default=NOW)

    def __str__(self):
        return self.make

my get view that generate an error

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

CodePudding user response:

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)
  • Related