Object of type ‘QuerySet‘ is not JSON serializable
在做前端ajax异步加载数据库数据的时候出现Object of type ‘QuerySet’ is not JSON serializable,大概意思是’QuerySet’对象不是json数据类型。 views.py
from django.shortcuts import render, redirect, reverse from django.http import JsonResponse from .models import Student def index(request): return render(request, index.html) def ajax_handle(request): students = Student.objects.all() data = { students: students } return JsonResponse(data)
urls.py
from django.urls import path, include from . import views app_name = new urlpatterns = [ path(index/, views.index, name=index), path(ajax_handle/, views.ajax_handle, name=ajax_handle), ]
index.html
<pre class="prettyprint"><code class="has-numbering" onclick="mdcp.copyCode(event)" style="position: unset;"><script src="{% static primary/js/jquery-1.8.2.min.js %}"></script> <script type="text/javascript"> {#当页面加载完毕,执行ajax#} $(function() { $.ajax({ url: /ajax_handle, type: get, // 默认参数可加可不加 dataType: json, // data: , // 请求参数 async: false // 默认为true 异步加载,false为同步加载 }).success(function (data) { {#// 这里用于处理数据#} alert(data) }) }) <div class="hljs-button {2}" data-title="复制" data-report-click="{ "spm":"1001.2101.3001.4259"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li><li style="color: rgb(153, 153, 153);">2</li><li style="color: rgb(153, 153, 153);">3</li><li style="color: rgb(153, 153, 153);">4</li><li style="color: rgb(153, 153, 153);">5</li><li style="color: rgb(153, 153, 153);">6</li><li style="color: rgb(153, 153, 153);">7</li><li style="color: rgb(153, 153, 153);">8</li><li style="color: rgb(153, 153, 153);">9</li><li style="color: rgb(153, 153, 153);">10</li><li style="color: rgb(153, 153, 153);">11</li><li style="color: rgb(153, 153, 153);">12</li><li style="color: rgb(153, 153, 153);">13</li><li style="color: rgb(153, 153, 153);">14</li><li style="color: rgb(153, 153, 153);">15</li><li style="color: rgb(153, 153, 153);">16</li></ul></pre> <h2><a name="t0"></a><a id="_57"></a>出错信息:</h2> <p><img src="https://img-blog.img.cn/20190724102808508.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2h1bWFuX3NvdWw=,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"></p> <h2><a name="t1"></a><a id="_60"></a>修改</h2>
view.py
from django.shortcuts import render, redirect, reverse from django.http import JsonResponse from django.core import serializers from .models import Student def index(request): return render(request, index.html) def ajax_handle(request): # 处理QuerySet students = serializers.serialize("json", Student.objects.all()) data = { students: students } return JsonResponse(data)
最终效果
下一篇:
Java如何提前终止for循环