Menu
CoddyTech

Una lista in JSON

Fa parte della sezione API JSON del percorso Django di Coddy. Lezione 2 di 19.

I programmi hanno bisogno di un URL che elenchi ogni attività. Un Task non può essere inserito così com'è in JSON, quindi ogni riga deve prima diventare un dizionario. Il metodo values() di QuerySet lo fa, usando esattamente le chiavi che indichi. Sul modello Book di una libreria:

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

È ancora un QuerySet, che il generatore JSON non riconosce. list() esegue la query e restituisce una semplice lista.

Infine, JsonResponse accetta solo un dizionario, a meno che tu non passi safe=False. Senza questo argomento, una lista genera un TypeError:

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

Sfida

Facile

Elenca ogni attività in formato JSON.

  1. In tasks/views.py, aggiungi una vista task_list che risponda con un elenco JSON, con un oggetto per ogni attività e le chiavi id, title, done e priority.
  2. In tasks/urls.py, aggiungi la route "api/tasks/" con il nome task_list.

Premi «Esegui»: si apre l’anteprima su /api/tasks/ e vengono elencate le attività Compra il latte, Scrivi il rapporto e Chiama la banca.

Provalo tu

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)

Tutte le lezioni di API JSON

Esercitati da solo: Playground Django