Python 在 Django 中创建 json 数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28740338/
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-08-19 03:40:32  来源:igfitidea点击:

Creating json array in django

pythonarraysjsondjango

提问by aquaman

I am trying to make a json array in django but I am getting error -

我正在尝试在 django 中创建一个 json 数组,但出现错误 -

In order to allow non-dict objects to be serialized set the safe parameter to False

and my views.py -

和我的 views.py -

def wall_copy(request):
    if True:
        posts = user_post.objects.order_by('id')[:20].reverse()
        return JsonResponse(posts) 

Basically user_post is a model a posts is the object of top 20 saved data. I want to send a json array but I am unable to convert posts into a json array. I also tried serializers but it didnt helped.

基本上 user_post 是一个模型,一个帖子是前 20 个保存数据的对象。我想发送一个 json 数组,但我无法将帖子转换为 json 数组。我也尝试过序列化程序,但没有帮助。

I am stuck help me please.

我卡住了请帮助我。

Thanks in advance.

提前致谢。

采纳答案by ger.s.brett

Would this solve your problem?

这能解决你的问题吗?

from django.core import serializers
def wall_copy(request):
    posts = user_post.objects.all().order_by('id')[:20].reverse()
    posts_serialized = serializers.serialize('json', posts)
    return JsonResponse(posts_serialized, safe=False) 

回答by S.Kozlov

Try to use valuesmethod: http://django.readthedocs.org/en/1.7.x/ref/models/querysets.html#django.db.models.query.QuerySet.values. It will produce dict-like representation for objects fields you need.

尝试使用方法:http: //django.readthedocs.org/en/1.7.x/ref/models/querysets.html#django.db.models.query.QuerySet.values。它将为您需要的对象字段生成类似 dict 的表示。

回答by Projesh Bhoumik

You can solve this by using safe=False:

您可以使用safe=False以下方法解决此问题:

    def wall_copy(request):
        posts = user_post.objects.all().order_by('id')[:20].reverse()

        return JsonResponse(posts, safe=False)

Note that it's not really unsafe- you just have to make sure on your own, that what you are trying to return can be converted to JSON.

请注意,它并不是真的不安全- 您只需要自己确保您尝试返回的内容可以转换为 JSON。

See JsonResponsedocs for reference.

请参阅JsonResponse文档以供参考。