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

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

本文介绍了如何将模型字段传递给JsonResponse对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Django 1.7引入了,我试图使用它来将值列表返回到我的ajax请求。

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

我想通过

>>> 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'}]

到JsonResponse对象。

to a JsonResponse object.

然而,我的尝试失败。

>>> 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

这可能是由于 Genre.objects.values()的不同数据结构。

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

如何做到这一点?

使用 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

有什么工作是

>>> 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?

推荐答案

为了将来参考, .values()返回一个 ValuesQuerySet 的行为像一个充满字典的迭代,所以使用 list()将会创建一个新的列表与其中的所有字典。这样,你可以创建一个新的dict并序列化。

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

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

IIRC,不安全一个JSON对象,以root身份列出,这可能是Django正在抱怨的原因。我找不到任何关于这一点的参考资料,不好意思。

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.

这篇关于如何将模型字段传递给JsonResponse对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 01:44