LoginSignup
1
1

More than 3 years have passed since last update.

pythonのmodels.pyで設定するテーブルを関連付ける

Last updated at Posted at 2019-11-28

やりたい事

pythonでdjangoを使ってブログを作っている。
models.pyにテーブルの設定を行う際に、
カテゴリー>記事のような親と子の関係にあるテーブルを作りたい。

やり方

各テーブルを紐づけるには、
各テーブルに存在する変数を用いる。
その際指定される変数をforeign_keyとして設定する。

実際にやってみた

ブログに投稿する記事には以下のclassとデータが入っている。
postクラスには
id,title,cantent,created_at,category
その際categoryクラスは別で作り、
id,name,created_at
で構成されている。

これらをデータ型も決めてコードに落とすと、

class Category(models.Model):
    name = models.CharField('カテゴリ名',max_length=255)
    created_at = models.DateTimeField('日付',default=timezone.now)

class Day(models.Model):
    title = models.CharField('タイトル',max_length=200)
    text = models.TextField('本文')
    date = models.DateTimeField('日付',default=timezone.now)
    category = models.ForeignKey(Category,verbose_name='カテゴリ',on_delete=models.PROTECT)

Dayクラスのcategoryインスタンスに代入しているのはmodelsにForeignKey関数を掛け合わせたものである。
その際に第一引数にcategoryを取り、verbose_nameでモデルの名前を任意のものに変えられます。
そしてon_deleteにPROTECT関数を代入する事でcategoryクラスで消去の処理を行った際でもpostクラスが存在する限り消去が行われなくなる(カテゴリを消しても投稿した記事は消えない)。

まとめ

ForeignKey関数を使う事で、
設定元が親テーブル、参照される側は小テーブルとなり関連づけられる。

参考記事
ForeignKey:https://www.sejuku.net/blog/54072
verbose_name:https://codor.co.jp/django/how-to-use-verbose-name

1
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
1
1