django webapi:dump django模型到JSON [英] django webapi: dump django model to JSON

查看:143
本文介绍了django webapi:dump django模型到JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将django模型转储为JSON格式。我试图这样做:

I'm trying to dump django models into JSON format. I've tried to do it like this:

import json
from api.models import User
from django.http import HttpResponse

def users(request):
    users = User.objects.all()
    return HttpResponse(json.dumps(users), content_type="application/json")

但它会抛出以下错误:

[<User: Paul McCartney>, <User: John Lennon>, <User: George Harrison>, <User: Ringo Starr>] is not JSON serializable

我知道我可以遍历所有对象并创建一个手册列表的字典,但我希望有任何更好的方法来做到这一点。有没有?

I know I can iterate through all objects and create a manual list of dictionaries, but I hope there's any better way to do that. Is there?

推荐答案

from django.core import serializers

data = serializers.serialize('json', User.objects.all())

你可以了解如何获取反序列化数据:

You can get an idea of how you are getting this data on deserialization:

import json
json.loads(data)

这篇关于django webapi:dump django模型到JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆