Python 如何将模型字段传递给 JsonResponse 对象

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

How to pass model fields to a JsonResponse object

pythonjsondjangohttpresponse

提问by speendo

Django 1.7 introduced the JsonResponse objects, which I try to use to return a list of values to my ajax request.

Django 1.7 引入了JsonResponse 对象,我尝试使用它向我的 ajax 请求返回值列表。

I want to pass

我想通过

>>> Genre.objects.values('name', 'color')
[{'color': '8a3700', 'name': 'rock'}, {'color': 'ffff00', 'name': 'pop'}, {'color': '8f8f00', 'name': 'electronic'}, {'color': '9e009e', 'name': 'chillout'}, {'color': 'ff8838', 'name': 'indie'}, {'color': '0aff0a', 'name': 'techno'}, {'color': 'c20000', 'name': "drum'n'bass"}, {'color': '0000d6', 'name': 'worldmusic'}, {'color': 'a800a8', 'name': 'classic'}, {'color': 'dbdb00', 'name': 'hiphop'}]

to a JsonResponse object.

到一个 JsonResponse 对象。

However, my attempts fail.

但是,我的尝试失败了。

>>> JsonResponse({'foo': 'bar', 'blib': 'blab'}) # works
<django.http.response.JsonResponse object at 0x7f53d28bbb00>

>>> JsonResponse(Genre.objects.values('name', 'color')) # doesn't work
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/home/marcel/Dokumente/django/FlushFM/env/lib/python3.4/site-packages/django/http/response.py", line 476, in __init__
    raise TypeError('In order to allow non-dict objects to be '
TypeError: In order to allow non-dict objects to be serialized set the safe parameter to False

This is probably due to the different data structure of Genre.objects.values().

这可能是由于Genre.objects.values().

How would this be done right?

这将如何正确完成?

[edit]

[编辑]

With safe=FalseI get

随着safe=False我得到

>>> JsonResponse(Genre.objects.values('name', 'color'), safe=False)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/home/marcel/Dokumente/django/FlushFM/env/lib/python3.4/site-packages/django/http/response.py", line 479, in __init__
    data = json.dumps(data, cls=encoder)
  File "/usr/lib/python3.4/json/__init__.py", line 237, in dumps
    **kw).encode(obj)
  File "/usr/lib/python3.4/json/encoder.py", line 192, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/usr/lib/python3.4/json/encoder.py", line 250, in iterencode
    return _iterencode(o, 0)
  File "/home/marcel/Dokumente/django/FlushFM/env/lib/python3.4/site-packages/django/core/serializers/json.py", line 109, in default
    return super(DjangoJSONEncoder, self).default(o)
  File "/usr/lib/python3.4/json/encoder.py", line 173, in default
    raise TypeError(repr(o) + " is not JSON serializable")
TypeError: [{'color': '8a3700', 'name': 'rock'}, {'color': 'ffff00', 'name': 'pop'}, {'color': '8f8f00', 'name': 'electronic'}, {'color': '9e009e', 'name': 'chillout'}, {'color': 'ff8838', 'name': 'indie'}, {'color': '0aff0a', 'name': 'techno'}, {'color': 'c20000', 'name': "drum'n'bass"}, {'color': '0000d6', 'name': 'worldmusic'}, {'color': 'a800a8', 'name': 'classic'}, {'color': 'dbdb00', 'name': 'hiphop'}] is not JSON serializable

What works is

有效的是

>>> JsonResponse(list(Genre.objects.values('name', 'color')), safe=False)
<django.http.response.JsonResponse object at 0x7f53d28bb9e8>

But isn't there a better way to generate a dict out of a Model object?

但是没有更好的方法可以从 Model 对象中生成 dict 吗?

采纳答案by Tiago

For future reference, .values()returns a ValuesQuerySetthat behaves like a iterable full of dictionaries, so using the list()will make a new instance of a listwith all the dictionaries in it. With that, you can create a new dict and serialize that.

为了将来参考,.values()返回 a ValuesQuerySet,它的行为就像一个充满字典的可迭代对象,因此使用list()将创建一个list包含所有字典的a 的新实例。有了它,您可以创建一个新的 dict 并对其进行序列化。

response = JsonResponse(dict(genres=list(Genre.objects.values('name', 'color'))))

IIRC, it's not safe to have a JSON object that has a list as root and that's probably why Django is complaining. I couldn't find any reference about that now to provide a source, sorry.

IIRC,将 JSON 对象作为根列表是不安全的,这可能是 Django 抱怨的原因。我现在找不到任何参考资料来提供来源,抱歉。