% python manage.py inspectdb yt_analysis_07
# This is an auto-generated Django model module.
# You'll have to do the following manually to clean this up:
# * Rearrange models' order
# * Make sure each model has one field with primary_key=True
# * Make sure each ForeignKey and OneToOneField has `on_delete` set to the desired behavior
# * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table
# Feel free to rename the models, but don't rename db_table values or field names.
from django.db import models
class YtAnalysis07(models.Model):
channel_id = models.CharField(max_length=40, blank=True, null=True)
channel_name = models.TextField(blank=True, null=True)
view_count = models.BigIntegerField(blank=True, null=True)
like_count = models.IntegerField(blank=True, null=True)
dislike_count = models.IntegerField(blank=True, null=True)
favorite_count = models.IntegerField(blank=True, null=True)
comment_count = models.IntegerField(blank=True, null=True)
video_count = models.IntegerField(blank=True, null=True)
class Meta:
managed = False
db_table = 'yt_analysis_07'
%
from rest_framework import serializers
from .models import YtAnalysis07 # モデルをインポート
class APISerializer(serializers.ModelSerializer):
class Meta:
model = YtAnalysis07 # 使用するモデル
fields = '__all__' # 処理対象にするフィールド(今回は全項目)
ビューの作成
API のビューを作成します。ざっくり言うとモデルからデータを抽出し、シリアライザに渡して JSON に変換し、その JSON データをレスポンスとして返します。
class based view の場合
from rest_framework import viewsets
from .serializers import APISerializer
from .models import YtAnalysis07
class DataListView(viewsets.ModelViewSet):
queryset = YtAnalysis07.objects.all() # モデルからデータを抽出するクエリセット
serializer_class = APISerializer # 使用するシリアライザ
urls.py の設定は下記の様にします。
from django.urls import path
from . import views
app_name = 'api'
urlpatterns = [
path('data-list/', views.DataListView.as_view({'get': 'list'}), name="data-list"),
]
function based view の場合
from rest_framework.decorators import api_view
from rest_framework.response import Response
from .serializers import APISerializer
from .models import YtAnalysis07
@api_view(['GET']) # GET のみに対応
def dataList(request):
api_data = YtAnalysis07.objects.all() # モデルからデータを抽出する
serializer = APISerializer(api_data, many=True) # シリアライザにデータを渡す
return Response(serializer.data) シリアル可されたデータを return で返す
urls.py の設定は下記の様にします。
from django.urls import path
from . import views
app_name = 'api'
urlpatterns = [
path('data-list/', views.dataList, name="data-list"),
]