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.
Development Specialist, Artist and Activist
Personal Website
where does windows 7 store windows 10 update files adobe creative suite 6 student uk FileMaker Pro 14 adobe photoshop elements 12 price comparison microsoft word and excel training courses