Django将Queryset序列化为JSON,以构造只包含字段信息和id的RESTful响应

2024-04-27 03:10:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我现在有一个Post模型,有“title”和“summary”字段。我正在检索所有帖子,并将它们作为JSON返回,作为RESTful API接口的一部分。

下面是基本方法

from django.core import serializers

def list_posts(request):
    posts = Post.objects.filter(owner=authenticated_user)
    serialized = serializers.serialize("json", posts, fields=('title', 'summary'))
    return HttpResponse(serialized, mimetype='application/json')

当我访问相应的路线时,我得到了如下的回复。

电流响应

[{"pk": 4, "model": "api.post", "fields": {"summary": "Testing", "title": "My Test"}}, {"pk": 5, "model": "api.post", "fields": {"summary": "testing again", "title": "Another test"}}]

从技术上讲,它包含了我的客户端构建模型所需的所有信息(我使用的是主干网,可以使用collection.parse来构建我所需的内容,但服务器端应该负责很好地构建响应)。令我困扰的是,它不像我在著名的API中看到的标准API响应。我认为下面这样的JSON响应会更“标准”。

期望响应

[{'summary': 'Testing', 'id': 4, 'title': 'My test'}, {'summary': 'My Test', 'id':5, 'title': 'Another test'}]

serialize的输出似乎不太适合将JSON中的模型实例集合作为API调用的响应返回,这似乎是一个相当常见的需求。我想返回字段信息和I d(或者pk,如果必须称为pk的话)。


Tags: 模型testapijsonfieldstitlemysummary
1条回答
网友
1楼 · 发布于 2024-04-27 03:10:35

您想要实现的是转储到json的字段子集。

您要做的是序列化整个django的ORM对象。不好的。

保持简单:

import json

posts = (Post.objects.filter(owner=authenticated_user)
                     .values('id', 'title', 'summary'))
json_posts = json.dumps(list(posts))

相关问题 更多 >