Django 将 Queryset 序列化为 JSON 以构建仅包含字段信息和 id 的 RESTful 响应 [英] Django Serialize Queryset to JSON to construct RESTful response with only field information and id

查看:15
本文介绍了Django 将 Queryset 序列化为 JSON 以构建仅包含字段信息和 id 的 RESTful 响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有一个带有标题"和摘要"字段的 Post 模型.我正在检索所有帖子并将它们作为 JSON 作为 RESTful API 接口的一部分返回.

I currently have a Post model with 'title' and 'summary' fields. I'm retrieving all the Posts and returning them as JSON as part of a RESTful API interface.

这是基本方法

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')

当我访问相应的路线时,我得到以下回复.

And I'm getting the following response back when I visit the corresponding route.

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

这在技术上包含我的客户端构建模型所需的所有信息(我正在使用 Backbone 并且可以使用 collection.parse 来构建我需要的东西,但服务器端应该负责很好地构建响应).令我烦恼的是,它看起来不像我习惯于在信誉良好的 API 中看到的标准 API 响应.我认为像下面这样的 JSON 响应会更标准".

This technically contains all the information my client-side needs to construct models (I'm using Backbone and could use collection.parse to construct what I need, but the server side should be responsible for structuring the response nicely). What troubles me about this is that it does not look like the standard API responses I'm used to seeing in reputable APIs. I think a JSON response like the following would be more 'standard'.

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

serialize 的输出似乎不太适合返回 JSON 中的模型实例集合作为 API 调用的响应,这似乎是一个相当普遍的需求.我想返回字段信息以及 id(或 pk,如果必须称为 pk).

The output from serialize does not seem quite right for returning a collection of model instances in JSON as a response from an API call and this seems like a fairly common need. I'd like to return the fields information along with the id (or pk, if it must be called pk).

推荐答案

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

What you want to achieve is subset of fields dumped to json.

您正在做的是序列化整个 django 的 ORM 对象.不好.

What you're doing is serializing whole django's ORM objects. Not good.

保持简单:

import json

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

这篇关于Django 将 Queryset 序列化为 JSON 以构建仅包含字段信息和 id 的 RESTful 响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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