Django: return rows from model as JSON

JSON

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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.

Development Specialist, Artist and Activist
Personal Website

Leave a Reply

Your email address will not be published.

*