Django的序列化的QuerySet以JSON构建,只有字段信息和id的RESTful响应 [英] Django Serialize Queryset to JSON to construct RESTful response with only field information and id

查看:940
本文介绍了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"}}]

这在技术上包含了所有我的客户端需要构建模型的信息(我使用的骨干网和可以使用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'}]

这是连载的输出似乎并不太适合从一个API调用的响应以JSON返回模型实例的集合,这似乎是一个相当普遍的需求。我想与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天全站免登陆