Why not login to Qiita and try out its useful features?

We'll deliver articles that match you.

You can read useful information later.

0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

django rest_frameworkでCRUD処理のAPI実装の流れ

Posted at

最近、djangoのrest_frameworkを使った実装をしていて
やり方を忘れないようにメモしておきます。

インストールはこちら(https://www.django-rest-framework.org/#installation)

pip install djangorestframework

bookというアプリの中のmodels.pyにBookという名前でモデルを作っている前提で話を進めます。
また、CRUD処理について、全ての処理を一括できるModelViewSetを用いて実装します。

step1:serializers.pyの作成&シリアライズクラスの作成

bookアプリにserializers.pyファイルを作成してください。
中身を、このように編集します。

serializers.py
from .models import Book #Bookモデル
from rest_framework import serializers

#Bookシリアライザ
class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book #モデルを指定
        fields = '__all__'

step2:views.pyにViewの作成

bookアプリのviews.pyに

views.py
from rest_framework import viewsets #ViewSet使用
from .serializers import BookSerializer 
from .models import Book


class BookViewSet(viewsets.ModelViewSet):
    serializer_class = BookSerializer 
    queryset = Book.objects.all()

step3.urls.pyにapiエンドポイント登録

bookアプリのurls.pyファイルを作成

urls.py
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from .views import (
    BookViewSet
)



router = DefaultRouter()
router.register('books', BookViewSet)

urlpatterns = [
    path('', include(router.urls)),#ViewSetのURLを追加
]

以上です。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?