Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

<object> is not JSON serializable django [closed]

I have a list of all product with all specifications . So now i want to send JsonResponse with that list with pagination of 10 product at a time. when i try to send all product

all_pro = Products.objects.all()
return HttpResponse(all_pro )

it gives me a error is not JSON serializable.

my product model

class Products(models.Model):
    product_name = models.CharField(max_length=50,null=True, blank=True)
    category = models.CharField(max_length=100, null=True, blank=True)
    price = models.IntegerField(default=0,null=True, blank=True)
    posting_date = models.DateTimeField(auto_now_add=True, blank=True)
    quantity = models.IntegerField(default=1,null=True, blank=True)
    extra_text = models.TextField(null=True, blank=True)
    color = models.CharField(max_length=50,null=True, blank=True)
    contact_number = models.CharField(max_length=50,null=True, blank=True)
    is_active = models.BooleanField(default=True)

So how can i send JsonResponse to front end. Thanks in advance. I am not using drf

I want to send Json Object

like image 977
vikrant Verma Avatar asked Jan 04 '23 22:01

vikrant Verma


1 Answers

All the above mentioned methods are good. But I prefer

all_pro = Products.objects.all().values('product_name', 'category', 'price')
return JsonResponse(list(all_pro))

JsonResponse can be imported from

from django.http import JsonResponse

This also makes sure your query fetches only required fields from database.

Sample response:

[{'product_name':'Data1', 'category':'cat1', 'price':10},{'product_name':'Data2', 'category':'cat2', 'price':5}]
like image 125
Arundas R Avatar answered Jan 12 '23 13:01

Arundas R