将 QuerySet 作为 JSON 返回?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30243101/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 17:54:03  来源:igfitidea点击:

Return QuerySet as JSON?

jsondjango

提问by Richard

I'm working in Django 1.8 and having trouble finding the modern way to do this.

我在 Django 1.8 中工作,但找不到现代方法来做到这一点。

This is what I've got, based on Googling and this blog post:

这就是我所得到的,基于谷歌搜索和这篇博文

results = PCT.objects.filter(code__startswith='a')
json_res = []
for result in results:
    json_res.append(result.as_dict())
return HttpResponse(json.dumps(json_res), content_type='application/json')

However this gives me 'PCT' object has no attribute 'as_dict'.

然而这给了我'PCT' object has no attribute 'as_dict'

Surely there must be a neater way by now?

现在肯定有更简洁的方法吗?

I was wondering if it was possible to use JSONResponsebut frustratingly, the docs give no example of how to use JSONRespose with a queryset, which must be the most common use case. I have tried this:

我想知道是否可以使用JSONResponse但令人沮丧的是,文档没有给出如何将 JSONRespose 与查询集一起使用的示例,这一定是最常见的用例。我试过这个:

results = PCT.objects.filter(code__startswith='a')
return JsonResponse(results, safe=False)

This gives [<PCT: PCT object>, <PCT: PCT object>] is not JSON serializable.

这给[<PCT: PCT object>, <PCT: PCT object>] is not JSON serializable.

回答by Leistungsabfall

Simplest solution without any additional framework:

没有任何额外框架的最简单的解决方案:

results = PCT.objects.filter(code__startswith='a').values('id', 'name')
return JsonResponse({'results': list(results)})

returns {'results': [{'id': 1, 'name': 'foo'}, ...]}

回报 {'results': [{'id': 1, 'name': 'foo'}, ...]}

or if you only need the values:

或者如果您只需要这些值:

results = PCT.objects.filter(code__startswith='a').values_list('id', 'name')
return JsonResponse({'results': list(results)})

returns {'results': [[1, 'foo'], ...]}

回报 {'results': [[1, 'foo'], ...]}

回答by wobbily_col

use values() to return a querydict, and pass that to json.dumps

使用 values() 返回一个 querydict,并将其传递给 json.dumps

values = PCT.objects.filter(code__startswith='a').values()
return HttpResponse(json.dumps(values), content_type='application/json')

https://docs.djangoproject.com/en/1.8/ref/models/querysets/#values

https://docs.djangoproject.com/en/1.8/ref/models/querysets/#values

回答by Adrian Ghiuta

Take a look at Django's serialization framework. It allows not only the XML format, but also JSON and YAML.

看看Django 的序列化框架。它不仅支持 XML 格式,还支持 JSON 和 YAML。