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:

1
{"books": [{"name": "book1", "url": "http://www.example.com/book1"}, {"name": "book2", "url": "http://www.example.com/book2"}]}

 

That’s all.

1 thought on “Django: return rows from model as JSON

Leave a Reply

Your email address will not be published. Required fields are marked *

*

This site uses Akismet to reduce spam. Learn how your comment data is processed.