pll*_*lee 7 python django json
这是问题:Django的序列化程序不支持字典,而simplejson不支持Django Querysets.请参阅使用simplejson进行JSON序列化Django模型
我想知道我的解决方案是否有任何问题.我有类似的东西:
people = People.objects.all().values('name', 'id')
json.dumps(list(people))
Run Code Online (Sandbox Code Playgroud)
我仍然是Python/Django的新手.被铸造QuerySet
到列表中的坏主意?使用DjangoJSONEncoder
其他主题中的建议更有效吗?
jfc*_*lvo 13
根据我自己的看法,您的解决方案完全有效且非常干净.
如果您需要列表(而不是字典列表),您也可以使用:
from django.utils import simplejson
people = People.objects.all().values_list('name', 'id')
simplejson.dumps(list(people))
Run Code Online (Sandbox Code Playgroud)
有时当json输出非常复杂时,我们通常使用带有*render_to_string*函数的json模板,例如:
context = {'people': People.objects.all().values('name', 'id')}
render_to_string('templates/people.json', context, context_instance=RequestContext(request))
Run Code Online (Sandbox Code Playgroud)
模板people.json可以是:
[
{% for person in people %}
{"name": {{ person.name }}, "id": {{ person.id }} }
{% if not forloop.last %} , {% endif %}
{% endfor %}
]
Run Code Online (Sandbox Code Playgroud)
但模板的使用仅限于比您更复杂的情况.我认为对于更容易的问题,一个好的解决方案是使用simplejson.dumps函数.