Web制作、Web開発の歩き方

初心者のためのDjango入門

■第2話:DjangoのModelとView

(最終更新日:2023.01.06)

Djangoフレームワークのイメージ
この記事は6分で読めます!
(絵が小さい場合はスマホを横に)

「MVTってどうなの?」

Ruby on Rails等、他のMVCフルスタックフレームワーク(FW)を使ったことある人はこう思うかもしれない。 しかしながら、前回の図で説明したように、 ファイルやディレクトリ構成こそMVCに分かれていないとは言え、やってることは同じである。 今回は、そんなDjangoのMVTモデル、ModelとViewの部分の具体的な機能、記述方法を説明する。 残りのTemplate自体の使い方とFormの値をデータベースに送る流れは、次回説明する。


1.DjangoのModel

DjangoのModelクラスはデータベースTableと紐づく。 そして、そのModelクラスのプロパティはDBのフィールド名(下記のtitleやnumber)を意味する。 まずはここを押さえた上で、下記のModelクラスのコードを見てみよう。

左側のコードを見て分かる通り、非常に簡単なコードでデータベースTableを作成することができる。 作りたいTableのフィールド(titleとnumber)を宣言し、型(CharField、IntegerField)や文字数(max_length)等を指定するだけである。 idは自動的に作成される。「〇〇 = models.CharField(primary_key=True)」と設定すれば、id以外でプライマリーキーを作成することもできる。 Table名は「アプリケーション名_クラス名」となる。(Metaクラスを使って、アプリケーション名が接頭辞にならない書き方もできる)

DjangoのModelと作成されるTable

作りたいデータベースTableを記述したら、コマンド上で「python manage.py makemigrations」 と入力してみよう。 すると、Modelの記述をより具体的にした中間ファイル(migrationファイル)がmigrationsフォルダ内に生成される。 migrationファイルの内容を見ると、Tableに対してどういう命令しているのかがより具体的に分かる。

DjangoのMigrationファイル

続けて「python manage.py migrate」と入力すると、中間ファイルから命令してDjango内部でSQLを実行(この場合Create Table)してくれる。 Modelクラスを作成し2つのコマンドを実行するという流れだけ覚えておこう。

この流れで1点大事なことを説明する。migrationファイルは前回との差分だけを新たなファイルとして作成する。 つまり、このファイル群はSQLを生成するための命令だけでなく、データベース操作履歴、バージョン管理をしているのである。 例えば、各々0001_〇〇.pyと順に付番され、バージョンを管理できる。バージョン管理というだけあって勿論ロールバックもできる。

2.DjangoのView

次にDjangoのViewを説明する。下記で最初の行に書いた@login_requiredはデコレーターと言って定義した関数に機能を付加できる。 この関数を実行するにはログインが必要という制約を加えている。もしログインしない状態で「list/ 」URLにアクセスした場合は、 ログイン画面に遷移させ、ログインをユーザーに促す。 (どのページに遷移させるかはsetting.pyに命令として書く。) また、関数内のobject_listでGameModel(Table)から得られるデータを辞書型で全て取得している。 このデータは次のrenderでHTMLtemplateファイル上で取得できるようにしている。 最後のrenderで表示に使うHTMLファイル(logged_in/list.html)を指定している。

urls.pyでは、このlistviewを「/list/」にルーティングしている。これが関数ベースで作るDjangoのViewである。 ModelとTemplate(HTML)の仲立ちをしていることが分かったと思う。

他にもクラスベースViewというものがあるが、やっていることは同じである。 ただし、関数ベースのViewよりも簡潔に書ける。クラスベースViewについては、また何処かで説明しよう。

DjangoのViewの例(上)、そのViewに対応するurls.py(下)

▼参考図書、サイト

 「Djangoのツボとコツがゼッタイにわかる本」 大橋亮太 秀和システム
 「現場で使えるDjango管理サイトのつくり方」 横瀬明仁
   Djangoでマイグレーション【前編】 Selfs Ryo Com
   【Django】views.py:renderメソッドの使い方 OFFICE54


Django Tutorial for Beginners ■ Episode 2: Django's Model and View (Last updated: 2023.01.06) Image of the Django framework You can read this article in 6 minutes! (If the image appears small, try turning your smartphone sideways.) "What’s the deal with MVT?" If you've used full-stack frameworks like Ruby on Rails, you might be wondering this. However, as explained in the previous diagram, while Django's file and directory structure doesn't strictly follow MVC, it essentially achieves the same purpose. In this episode, we’ll explore Django’s MVT architecture—specifically the **Model** and **View** parts. We’ll cover Templates and how to send form data to the database in the next episode. [Contents] Django Model Django View 1. Django Model Django's Model class maps directly to a database table. Each property of the Model class represents a field in the table, such as title or number. As shown on the left, you can define a table with just a few lines of code. Declare the fields you want (like title and number), specify the type (e.g., CharField, IntegerField) and options like max_length. The primary key id is created automatically. You can also set a different field as the primary key by using models.CharField(primary_key=True). Table names default to "appname_classname", but this can be overridden using the Meta class. Django Model and the Corresponding Table Once you've written your Model, run the command python manage.py makemigrations. This will generate an intermediate migration file in the migrations folder based on your model. You can view this file to better understand the specific SQL-like instructions being prepared. Django Migration File Next, run python manage.py migrate to execute the SQL commands (e.g., CREATE TABLE) internally in Django. One important thing to note: each migration file captures the differences from the previous version. This means migrations serve not only to apply changes but also to version control your database schema. Files are sequentially numbered like 0001_***.py, allowing rollbacks and upgrades. 2. Django View Now let’s look at Views in Django. The first line in the example below uses @login_required, a *decorator* that adds functionality to the defined function. This one requires the user to be logged in before accessing the view. If someone tries to access /list/ without being logged in, Django will redirect them to the login page. (You can specify the redirect URL in settings.py.) Inside the function, object_list retrieves all data from the GameModel table as a dictionary. This data is then passed to the HTML template via the render function, which specifies logged_in/list.html as the view. In urls.py, this view is routed to the /list/ URL. This is an example of a function-based view (FBV) in Django—serving as the bridge between the Model and the Template (HTML). There's also something called Class-Based Views (CBV), which do essentially the same thing, but in a more concise manner. We’ll cover CBVs in a future article. Example of a Django View (top) and its corresponding urls.py (bottom) ▼ References  “Django no Tsubo to Kotsu ga Zettai ni Wakaru Hon” by Ryota Ohashi, SHUWA System  “Gemba de Tsukaeru Django Kanri Site no Tsukurikata” by Akihito Yokose    Django Migrations [Part 1] - Selfs Ryo Com    [Django] How to Use the render Method in views.py - OFFICE54