javascript - Django如何将查询集转换为json?
问题描述
我的views.py 看起来像这样:
def index(request):
mydata = mymodel.objects\
.values('district')\
.annotate(total=Count('district'))\
.order_by('total')
aggregate = json.dumps(list(mydata), cls=DjangoJSONEncoder)
context = {'aggregate': aggregate}
return render(request, 'polls/index.html',context)
在我的 index.html 中,我的代码是这样的:
var aggregate = '{{ aggregate }}'
但是,当我console.log(aggregate)
在浏览器中这样做时,它给了我这个字符串:
[{"district": "ISLINGTON", "total": 663}, {"district": "HACKNEY", "total": 669}, {"district": "HARINGEY", "total": 1230}, {"district": "WALTHAM FOREST", "total": 1947}]
我希望这应该是 JSON 格式。我还在学习 Django,有人可以帮我吗?提前致谢!