无法使用ajax显示查询集

Adi*_*ngh 6 django ajax django-templates

我在使用ajax时无法显示queryset

这是我的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)
Run Code Online (Sandbox Code Playgroud)

这是我的ajax脚本:

<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>
Run Code Online (Sandbox Code Playgroud)

我该怎么做才能解决上面的问题?
提前致谢

Ala*_*air 14

如果您查看来自Django的错误消息,您将看到它抱怨查询集不是JSON可序列化的.对于ajax请求,您可以在使用Web浏览器的开发工具时查看响应DEBUG=True.

首先要做的是使用values(),它返回一个查询集,其中包含查询集中每个实例的字典.其次,您需要将查询集强制转换为列表.

queryset = StoreProduct.objects.get_size(productid)
values_list = list(queryset.values())
Run Code Online (Sandbox Code Playgroud)