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
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}]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With