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.
Here's the basic approach
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.
Current Response
[{"pk": 4, "model": "api.post", "fields": {"summary": "Testing", "title": "My Test"}}, {"pk": 5, "model": "api.post", "fields": {"summary": "testing again", "title": "Another test"}}]
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'.
Desired Response
[{'summary': 'Testing', 'id': 4, 'title': 'My test'}, {'summary': 'My Test', 'id':5, 'title': 'Another test'}]
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).