Closed4

Django Model基礎(学習メモ)

いもけんいもけん

Modelの利用

CREATE文

CREATE TABLE "テーブル名" (
   カラム1 データ型 {制約},
   カラム2 データ型 {制約},
);

上記をModelに書き直す

Modelクラス

class テーブル名(Model):
    カラム名1 = データ型(制約)
    カラム名2 = データ型(制約)

データベースのテーブルは、Modelクラスのクラス名に置き換える。

データベース Modelクラス
テーブル名 クラス名(実際は、「アプリ名_クラス名」)
カラム名 クラス変数名
データ型 クラス変数に代入するオブジェクト
制約 Fieldクラスのオプション
いもけんいもけん

Model作成

作成するテーブル

カラム名 データ型 用途
code INTEGER(整数) 商品コード
name TEXT(テキスト) 商品名
price INTEGER(整数) 価格

Djangoでは、Modelクラスを作成すると、テーブルを自動で生成することができる。

Modelクラス作成例

myapp/models.py
from django.db import models
 
# Create your models here.
class item(models.Model):          # 追加
    code = models.IntegerField()   # 追加
    name = models.TextField()      # 追加
    price = models.IntegerField()  # 追加

クラス名にはテーブル名と同じ「item」、クラス変数(code/name/price)にカラム名を使用する。クラス変数に代入するオブジェクト型でデータ型を表している。整数型なら「IntegerField( )」を、テキスト型なら「TextField( )」を使用する。
ほかにも、models.CharField( )やmodels.DateField( )など、データベースのカラム型に相当するものが、DjangoのModelクラスには用意されている。
今回は制約をかけていないが、デフォルトでNOT NULL制約は有効になっている。

いもけんいもけん

Modelとデータベースの同期

マイグレーション

作成したModelクラスをもとにデータベスに反映し同期する作業。
次のコマンドをプロジェクトディレクトリで順番に実行することでマイグレーションを実行できる。

1, python manage.py makemigrations Webアプリケーション名
2, python manage.py migrate

マイグレーションの実行例

$ python manage.py makemigrations myapp
Migrations for 'myapp':
  myapp/migrations/0001_initial.py
    - Create model item
$ python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, myapp, 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 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 myapp.0001_initial... OK                    <--myappが初期化されている
  Applying sessions.0001_initial... OK

確認のためにSQLite3を起動

$ sqlite3 db.sqlite3
sqlite> .table
auth_group                  django_admin_log          
auth_group_permissions      django_content_type       
auth_permission             django_migrations         
auth_user                   django_session            
auth_user_groups            myapp_item                
auth_user_user_permissions

上記にて”myapp_item”が作成されているのが確認できる。

いもけんいもけん

Modelを使用して表示

テンプレートファイルの作成

templates配下にitem.htmlを作成する。

templates/item.html
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>{{ item.name }}</title>
<head>
<body>
<center>
<h2>商品検索結果</h2>
<table border=1>
    <tbody>
        <tr>
            <th>商品コード</th>
            <td>{{ item.code }}</td>
        </tr>
        <tr>
            <th>商品名</th>
            <td>{{ item.name }}</td>
        </tr>
        <tr>
            <th>価格</th>
            <td>{{ item.price }}円</td>
        </tr>
    </tbody>
</table>
<br>
</center>
</body>
</html>

Viewの修正

URLで指定される「item_code」も引数に加え、どの商品の情報を表示するのかを、URLに商品IDを追加することで指定できるようにする

myapp/view.py
from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import render
from datetime import datetime
from .models import item   #追加

...省略...
 
↓以下追加
def show_item(request,item_code):
    # item_codeで指定された商品コードでデータベースを検索しデータを取得
    Item = item.objects.get(code=item_code)
    context = {'item':Item, }
    return render(request, 'item.html', context)

URLディスパッチャーの追加

myapp/urls.py
from django.urls import path
from django.conf.urls import url
from . import views
 
urlpatterns = [
    path('' , views.index, name = 'index' ),
    path('foo' , views.foo, name = 'foo' ), 
    path('hello', views.hello, name='hello'),
    path('item/<int:item_code>', views.show_item, name='show_item'),  #追加
]

サーバーを起動しブラウザで動作確認

http://127.0.0.1:8000/myapp/item/101
このスクラップは2023/01/03にクローズされました