Django-rest-framework的用法

这篇文章的摘要

提供使用Django REST Framework的方法说明。

安装Django REST Framework

安装django-rest-framework。

// django-rest-frameworkのインストール
$ pip3 install djangorestframework

Django REST Framework的用法

Django REST Framework的配置。

INSTALLED_APPS = [
    'rest_framework', # 追加
    'api' # 追加
]
from django.contrib import admin
from django.urls import path, include # 追加

urlpatterns = [
    path('api-auth/', include('rest_framework.urls')), # 追加
    path('api/', include('api.urls')), # 追加
]

创建模型(API)。

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)

创建序列化器(API)。

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__'

通过使用视图集创建API来创建views。

from rest_framework import viewsets
from .models import Food
from .serializers import FoodSerializer

class FoodViewSet(viewsets.ModelViewSet):
    queryset = Food.objects.all()
    serializer_class = FoodSerializer

创建URL(API)

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)),
]
广告
将在 10 秒后关闭
bannerAds