Django将Queryset序列化为JSON以仅使用字段信息和id构建RESTful响应

dgh*_*dgh 17 python api django rest json

我目前有一个带有'title'和'summary'字段的Post模型.我正在检索所有帖子并将它们作为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')
Run Code Online (Sandbox Code Playgroud)

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

目前的回应

[{"pk": 4, "model": "api.post", "fields": {"summary": "Testing", "title": "My Test"}}, {"pk": 5, "model": "api.post", "fields": {"summary": "testing again", "title": "Another test"}}]
Run Code Online (Sandbox Code Playgroud)

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

期望的回应

[{'summary': 'Testing', 'id': 4, 'title': 'My test'}, {'summary': 'My Test', 'id':5, 'title': 'Another test'}]
Run Code Online (Sandbox Code Playgroud)

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

Krz*_*arz 19

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

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

把事情简单化:

import json

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

  • 为此,我的朋友,专注于[Django REST Framework](http://www.django-rest-framework.org/). (2认同)