Menu
CoddyTech

A List as JSON

Part of the JSON APIs section of Coddy's Django journey. Lesson 2 of 19.

Programs need one URL that lists every task. A Task cannot go into JSON as it is, so each row must become a dictionary first. The QuerySet method values() does that, with exactly the keys you name. On a bookshop's Book model:

>>> Book.objects.values("title", "year")
<QuerySet [{'title': 'Dune', 'year': 1965}, {'title': 'Emma', 'year': 1815}]>

That is still a QuerySet, which the JSON writer does not know. list() runs the query and gives a plain list.

Last, JsonResponse takes only a dictionary unless you pass safe=False. A list without it raises TypeError:

return JsonResponse(["red", "green", "blue"], safe=False)
challenge icon

Challenge

Easy

List every task as JSON:

  • A view task_list that answers a JSON list, one object per task with the keys id, title, done and priority.
  • The route "api/tasks/", named task_list.

Press Run: the preview opens /api/tasks/ and lists the three tasks.

Try it yourself

from django.http import JsonResponse
from django.shortcuts import render

from .models import Task


def home(request):
    return render(request, "tasks/home.html", {"tasks": Task.objects.all()})


def stats(request):
    data = {
        "total": Task.objects.count(),
        "done": Task.objects.filter(done=True).count(),
    }
    return JsonResponse(data)

All lessons in JSON APIs

Practice on your own: Django playground