如何从 Paginator 的页面 return JsonResponse? Page 类型的对象 JSON 不可序列化

How to I return JsonResponse from Paginator's page? Object of type Page is not JSON serializable

(这是我第一个 Whosebug 问题)

我想 return 来自字典“上下文”的 JsonResponse(似乎是分页器页面) 编码如下:

myposts = userposts.all().values()
myfollowers = userfollowers.ffollowers.all()
myfollowings = userfollowers.ffollowings.all()

context = {"posts": page_obj,
    "loops": range(1, totalpages + 1),
    "user": uprofile.username,
    "myposts": list(myposts),
    "mypostsnum": len(userposts.all()),
    "myfollowers": list(myfollowers),
    "myfollowersnum": len(userfollowers.ffollowers.all()),
    "myfollowings": list(myfollowings),
    "myfollowingsnum": len(userfollowers.ffollowings.all())
}

这是我使用的return:

return JsonResponse(context, safe=False)

我得到的结果:

Object of type Page is not JSON serializable

我的问题是如何从 'context' 获取 JsonResponse?

问题出在 "posts": page_objpage_obj 是一个模型的实例。喜欢 page_obj = Post.objects.get(pk=1).

JsonResponse 将在您的上下文中调用 json.dumps() 并且失败,因为它不知道如何处理对象。

我建议您为此使用 Django rest framework。序列化器就是用来解决这个问题的。

您正在尝试序列化查询集,而 django 有预定义的序列化程序来完成这项工作。

from django.core.serializers import serialize

data = {
            'context': serialize("json", context)
        }
       
return JsonResponse(data)