Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to display queryset using ajax and Django

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

like image 793
asing177 Avatar asked Dec 18 '15 15:12

asing177


2 Answers

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())
like image 183
Alasdair Avatar answered Nov 15 '22 04:11

Alasdair


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.

like image 21
Shang Wang Avatar answered Nov 15 '22 02:11

Shang Wang