Menu
CoddyTech

プロジェクト:優先順位

CoddyのDjangoジャーニー「JSON API」セクションの一部。レッスン 15/19。

自分で機能を追加してみましょう。各タスクにはpriorityがあり、low、normal、highのいずれかです。APIではプログラムから優先度を1つ指定できるようにし、4つ目の優先度を勝手に作れないようにする必要があります。

必要なものはすべて揃っています。フィルターにはrequest.GET.get()を使えます。複数回フィルターできるQuerySetと、400を返すerrors辞書もあります。

許可される値はモデルにあります。Task.PriorityはTextChoicesクラスで、Task.Priority.valuesはリスト["low", "normal", "high"]です。このリストと照合すれば、後でモデルに優先度が追加されても、ビューを変更せずに受け付けられます。

challenge icon

チャレンジ

中級

APIに優先度を追加します。

  • /api/tasks/?priority=highは優先度が高いタスクのみを一覧表示し、?done=と組み合わせて使用できます。例:?priority=high&done=false。
  • low、normal、high以外の優先度を指定したPOSTには、"priority"の下にエラーを含む400が返され、何も保存されません。
  • 優先度を指定しない場合は、引き続きnormalになります。

Runを押すと、プレビューに優先度が高いタスクが1件表示されます。

自分で試してみよう

import json

from django.http import HttpResponse, JsonResponse
from django.shortcuts import get_object_or_404, render
from django.utils.decorators import method_decorator
from django.views import View
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_GET, require_http_methods

from .models import Task


def task_to_dict(task):
    return {
        "id": task.id,
        "title": task.title,
        "done": task.done,
        "priority": task.priority,
    }


def home(request):
    return render(request, "tasks/home.html")


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


def task_row(request, pk):
    task = get_object_or_404(Task, pk=pk)
    return render(request, "tasks/list.html#task-row", {"task": task})


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


@csrf_exempt
@require_http_methods(["GET", "POST"])
def task_list(request):
    if request.method == "POST":
        try:
            data = json.loads(request.body)
        except json.JSONDecodeError:
            return JsonResponse({"error": "The body is not valid JSON."}, status=400)
        errors = {}
        title = data.get("title", "").strip()
        if not title:
            errors["title"] = "This field is required."
        if errors:
            return JsonResponse({"errors": errors}, status=400)
        task = Task.objects.create(
            title=title,
            priority=data.get("priority", "normal"),
        )
        return JsonResponse(task_to_dict(task), status=201)
    tasks = Task.objects.all()
    done = request.GET.get("done")
    if done == "true":
        tasks = tasks.filter(done=True)
    elif done == "false":
        tasks = tasks.filter(done=False)
    return JsonResponse([task_to_dict(task) for task in tasks], safe=False)


def not_found():
    return JsonResponse({"error": "Task not found"}, status=404)


@method_decorator(csrf_exempt, name="dispatch")
class TaskDetail(View):
    def get(self, request, pk):
        task = Task.objects.filter(pk=pk).first()
        if task is None:
            return not_found()
        return JsonResponse(task_to_dict(task))

    def patch(self, request, pk):
        task = Task.objects.filter(pk=pk).first()
        if task is None:
            return not_found()
        data = json.loads(request.body)
        if "title" in data:
            task.title = data["title"]
        if "done" in data:
            task.done = data["done"]
        task.save()
        return JsonResponse(task_to_dict(task))

    def delete(self, request, pk):
        task = Task.objects.filter(pk=pk).first()
        if task is None:
            return not_found()
        task.delete()
        return HttpResponse(status=204)

JSON APIのすべてのレッスン

自分で練習してみよう: Djangoプレイグラウンド