
Overview
I’ll demostrate in this article how to create a simple view to return JSON formatted rows from your model.
Demonstration
Lets imagine we have a model named Book with two fields: Name and Url. The following view function _def BooksList(request):_will return list of items as JSON.
views.py
from django.utils import simplejson from myapp.models import Book
def response\_mimetype(request): if "application/json" in request.META\['HTTP\_ACCEPT'\]: return "application/json" else: return "text/plain"
def BooksList(request): books = \[\] # you can change .all() to .filter() # ex: Book.objects.filter(user=request.user.id): for obj in Book.objects.all(): books += \[{ 'name': obj.name, 'url': obj.url }\] data = {"books": books} response = JSONResponse(data, {}, response\_mimetype(request)) response\['Content-Disposition'\] = 'inline; filename=files.json' return response
This sample will return something like this:
{"books": \[{"name": "book1", "url": "http://www.example.com/book1"}, {"name": "book2", "url": "http://www.example.com/book2"}\]}
That’s all.
