Python 如何将模型字段传递给JsonResponse对象
Django 1.7引入了,我尝试使用它向ajax请求返回一个值列表 我想通过考试Python 如何将模型字段传递给JsonResponse对象,python,json,django,httpresponse,Python,Json,Django,Httpresponse,Django 1.7引入了,我尝试使用它向ajax请求返回一个值列表 我想通过考试 >>> Genre.objects.values('name', 'color') [{'color': '8a3700', 'name': 'rock'}, {'color': 'ffff00', 'name': 'pop'}, {'color': '8f8f00', 'name': 'electronic'}, {'color': '9e009e', 'name': 'chillout'},
>>> 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对象
然而,我的尝试失败了
>>> 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
有效的是
>>> JsonResponse(list(Genre.objects.values('name', 'color')), safe=False)
<django.http.response.JsonResponse object at 0x7f53d28bb9e8>
JsonResponse(列表(Genre.objects.values('name','color')),safe=False)
但是,没有更好的方法从模型对象生成dict吗?为了将来的参考,
.values()
返回一个ValuesQuerySet
,其行为类似于一个充满字典的iterable,因此使用list()
将创建一个包含所有字典的列表的新实例。这样,您就可以创建一个新的dict并将其序列化
response = JsonResponse(dict(genres=list(Genre.objects.values('name', 'color'))))
IIRC,将列表作为根的JSON对象是不安全的,这可能就是Django抱怨的原因。很抱歉,我现在找不到任何关于这个的参考来提供源代码。要在使用Genres.object.values('name','color')检索时将非描述性值传递给JsonResponse,只需将safe参数设置为false,它就会返回JSON
from django.http import JsonResponse
def django_json(request):
data = Genres.object.values('name','color')
return JsonResponse(data, safe=False)
这将返回指定值的JSON列表。查看我的文章,了解更多关于如何工作的详细信息
或者,如果希望将queryset作为JSON返回,可以使用Djangos core序列化程序,如下所示:
from django.core.serializers import serialize
from django.http import JsonResponse
from .models import Genre
def django_models_json(request):
qs = Genre.objects.all()
data = serialize("json", qs, fields=('name', 'color'))
return JsonResponse(data)
这将返回与上面相同的结果。您是否尝试按照错误消息所述执行操作?@speendosafe=False是否也存在相同的错误?可能在将ValuesQuerySet
传递给list()
:JsonResponse(list(Genre.objects.values('name','color')))
@speendo:.values()返回字典列表后尝试。如果需要,您可以创建一个新的dictionarydict(genres=Genre.objects…
并使用它。我在这里只是猜测一下,但现在可能list()
就可以了dict(genres=list(Genre.object…)
@Tiago。只是我一个人,还是从django模型生成JSON响应对象非常棘手?不管怎样-你想制定一个答案让我接受吗?at的答案使用了django.core中的序列化器
,这可能很方便地获得整个模型,但必须将已经序列化的JSON传递给JsonResponse似乎很奇怪。我更喜欢这个答案的技巧,尤其是当我只需要每个模型中的几个字段时。我一直在寻找这样的答案!在serialize函数中,您可以传递一个可选的fields
参数,该参数将只返回指定的字段,而不是作为JSON返回整个对象。
from django.core.serializers import serialize
from django.http import JsonResponse
from .models import Genre
def django_models_json(request):
qs = Genre.objects.all()
data = serialize("json", qs, fields=('name', 'color'))
return JsonResponse(data)