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 tutte le attività. Un Task non può essere inserito così com’è in JSON, quindi ogni riga deve prima diventare un dizionario. Il metodo values() di QuerySet fa proprio questo, con 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}]>

Si tratta ancora di un QuerySet, che il writer JSON non conosce. list() esegue la query e restituisce una normale lista.

Infine, JsonResponse accetta solo un dizionario, a meno che tu non passi safe=False. Una lista senza questo parametro genera TypeError:

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

Sfida

Facile

Elenca ogni attività in formato JSON:

  • Una vista task_list che restituisce un elenco JSON, con un oggetto per ogni attività e le chiavi id, title, done e priority.
  • Il percorso "api/tasks/", denominato task_list.

Premi Run: l'anteprima apre /api/tasks/ ed elenca le tre attività.

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