I'm not able to display queryset while using ajax
here is my views.py
:
if request.user.is_authenticated():
productid = request.GET.get('productId')
print productid
if request.is_ajax():
try:
queryset= StoreProduct.objects.get_size(productid)
except:
queryset= None
data = {
"queryset" : queryset
}
return JsonResponse(data)
Here is my ajax script:
<script type="text/javascript">
function getStoreView(event, productId) {
event.preventDefault();
var data = {
productId : productId
}
$.ajax({
type: "GET",
url: "{% url 'storeView' user=store.user %}",
data: data,
success: function(data) {
console.log(data.queryset)
},
error: function(response, error) {
alert(error);
}
});
};
</script>
What should I do to solve the problem above?
Thanks in advance
If you look at the error message from Django, you will see it complaining that the queryset is not JSON serializable. For ajax requests, you can see the response using your web browser's development tools when DEBUG=True
.
The first thing to do is to use values()
, which returns a queryset containing dictionaries for each instance in the queryset. Secondly, you need to coerce the queryset into a list.
queryset = StoreProduct.objects.get_size(productid)
values_list = list(queryset.values())
You cannot send queryset directory as json, because json is just a string. You could use django serializer to apply to your queryset:
from django.core import serializers
serialized_qs = serializers.serialize('json', queryset)
data = {"queryset" : serialized_qs}
return JsonResponse(data)
Also in your javascript you have to do data['queryset']
to access your queryset as json.
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