django webapi:将django模型转储到JSON

duc*_*cin 1 django json model

我正在尝试将django模型转换为JSON格式.我试过这样做:

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")
Run Code Online (Sandbox Code Playgroud)

但它会抛出以下错误:

[<User: Paul McCartney>, <User: John Lennon>, <User: George Harrison>, <User: Ringo Starr>] is not JSON serializable
Run Code Online (Sandbox Code Playgroud)

我知道我可以迭代所有对象并创建一个手动的词典列表,但我希望有更好的方法来做到这一点.在那儿?

Aks*_*aaj 5

from django.core import serializers

data = serializers.serialize('json', User.objects.all())
Run Code Online (Sandbox Code Playgroud)

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

import json
json.loads(data)
Run Code Online (Sandbox Code Playgroud)