LoginSignup
0
1

More than 3 years have passed since last update.

Djangoを使ったWEBアプリケーションの開発【モデル定義編】

Posted at

テンプレート追加編の続き

モデルの定義

現在作成しているpostsという機能は、ブログなどの記事を入力するための機能をイメージしているため、タイトル・記事・日時・画像を格納するデータベースが必要になります。
これをmodels.pyに追記していきます。

models.py
from django.db import models

#Postというクラスとして定義していきます。
class Post(models.Model): 

    #タイトルについての定義、文字列型のためCharFieldを使用
    #max_lengthで文字数制限をすることが可能
    title = models.CharField(max_length=100)

    #日時についての定義、日付データのためDateTimeFieldを使用
    published = models.DateTimeField() 

    #画像データについての定義、画像データのためImageFieldを使用
    #引数として画像データの保存先を指定できる(今回は、mediaフォルダを指定)
    image = models.ImageField(upload_to='media/') 

    #文章についての定義、テキスト型のためTextFieldを使用
    #長い文章のときに使用
    body = models.TextField()

次に、models.pyを基にデータベースのテーブルを作成するコマンドを実行する。

$ python3.6 manage.py makemigrations

Migrations for 'posts':
  posts/migrations/0001_initial.py
    - Create model Post

新しい定義ファイルが有った場合、データベースに投入するためのファイルを作成してくれる。

続いて新しくできたファイルを読み込みテーブルを作成する。

$ python3.6 manage.py migrate

Operations to perform:
  Apply all migrations: admin, auth, contenttypes, posts, sessions
Running migrations:
  Applying posts.0001_initial... OK

データベースにアクセスしてテーブルが存在するかを確認する。

$ sqlite3 db.sqlite3

SQLite version 3.31.1 2020-01-27 19:55:54
Enter ".help" for usage hints.
sqlite> .tables
auth_group                  django_admin_log          
auth_group_permissions      django_content_type       
auth_permission             django_migrations         
auth_user                   django_session            
auth_user_groups            posts_post #新しく作成されたテーブル                
auth_user_user_permissions

「posts_post」というテーブルが作成されたことがわかる。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1