% 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"),
]
% python manage.py inspectdb yt_trend_channel
# 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 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 YtTrendChannel(models.Model):
channel_id = models.CharField(max_length=30, blank=True, null=True)
view_count = models.CharField(max_length=20, blank=True, null=True)
join_date = models.CharField(max_length=20, blank=True, null=True)
country = models.CharField(max_length=20, blank=True, null=True)
channel_name = models.CharField(max_length=100, blank=True, null=True)
thumbnail_url = models.CharField(max_length=50, blank=True, null=True)
subscriber_count = models.CharField(max_length=20, blank=True, null=True)
data_date = models.CharField(max_length=8, blank=True, null=True)
class Meta:
managed = False
db_table = 'yt_trend_channel'
%
class 文を models.py にコピーすると Django でモデルとして使える様になります。その際に 1 つ「primary_key=True」のフィールドを持つ必要がありますので確認してください。
(sample_venv) % pip install psycopg2-binary
Collecting psycopg2-binary
Downloading https://files.pythonhosted.org/packages/2c/85/c26507efb110f5a91f503e517f1db55f12ebecb001ff224b2cea234a07ef/psycopg2_binary-2.8.6-cp38-cp38-macosx_10_9_x86_64.macosx_10_9_intel.macosx_10_10_intel.macosx_10_10_x86_64.whl (1.5MB)
|████████████████████████████████| 1.5MB 7.1MB/s
Installing collected packages: psycopg2-binary
Successfully installed psycopg2-binary-2.8.6
WARNING: You are using pip version 19.2.3, however version 21.0.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
(sample_venv) %
% python manage.py runserver
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
April 23, 2021 - 21:27:24
Django version 3.2, using settings 'sample_django_project.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
特に問題がなければ上記の様なログが表示されるはずです。
そしてブラウザの URL バーに「http://127.0.0.1:8000/」と入力して下記の画面が表示されたら OK です。
% python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying admin.0003_logentry_add_action_flag_choices... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying auth.0009_alter_user_last_name_max_length... OK
Applying auth.0010_alter_group_name_max_length... OK
Applying auth.0011_update_proxy_permissions... OK
Applying auth.0012_alter_user_first_name_max_length... OK
Applying sessions.0001_initial... OK