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.
[{"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'.
[{'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).
To serialize a queryset or list of objects instead of a single object instance, you should pass the many=True flag when instantiating the serializer. You can then pass a queryset or list of objects to be serialized.
Django's serialization framework provides a mechanism for “translating” Django models into other formats. Usually these other formats will be text-based and used for sending Django data over a wire, but it's possible for a serializer to handle any format (text-based or not).
Serializers in Django REST Framework are responsible for converting objects into data types understandable by javascript and front-end frameworks. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.
What you want to achieve is subset of fields dumped to json.
What you're doing is serializing whole django's ORM objects. Not good.
Keep it simple:
import json
posts = (Post.objects.filter(owner=authenticated_user)
.values('id', 'title', 'summary'))
json_posts = json.dumps(list(posts))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With