この記事の概要
django-rest-frameworkを使う方法を記載する。
django-rest-frameworkのインストール
django-rest-frameworkのインストール
// django-rest-frameworkのインストール
$ pip3 install djangorestframework
django-rest-frameworkの使い方
django-rest-frameworkの設定(config)
config/settings.py
INSTALLED_APPS = [
'rest_framework', # 追加
'api' # 追加
]
config/urls.py
from django.contrib import admin
from django.urls import path, include # 追加
urlpatterns = [
path('api-auth/', include('rest_framework.urls')), # 追加
path('api/', include('api.urls')), # 追加
]
modelsの作成(api)
api/models.py
from django.db import models
from django.utils import timezone # timezoneのインポート
class Food(models.Model):
def __str__(self):
return self.name
name = models.CharField(verbose_name='名前', null=True, blank=True, max_length=64)
created_at = models.DateTimeField(verbose_name='作成日時', default=timezone.now)
updated_at = models.DateTimeField(verbose_name='編集日時', blank=True, null=True)
serializersの作成(api)
api/serializers.py
from rest_framework import serializers
from .models import Food
class FoodSerializer(serializers.ModelSerializer):
created_at = serializers.DateTimeField(format="%Y-%m-%d %H:%M", read_only=True)
updated_at = serializers.DateTimeField(format="%Y-%m-%d %H:%M", read_only=True)
class Meta:
model = Food
fields = '__all__'
viewsの作成(api)※ビューセットによる作成
api/views.py
from rest_framework import viewsets
from .models import Food
from .serializers import FoodSerializer
class FoodViewSet(viewsets.ModelViewSet):
queryset = Food.objects.all()
serializer_class = FoodSerializer
urlsの作成(api)
api/urls.py
from django.urls import path, include
from rest_framework import routers
from .views import FoodViewSet
foodRouter = routers.DefaultRouter()
foodRouter.register('food', FoodViewSet)
urlpatterns = [
path('', include(foodRouter.urls)),
]