6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Django で model のプライマリーキーを設定する

Last updated at Posted at 2019-02-17

Django で model を作成すると、id が プライマリーキーになります。
テーブルの構造はこのようになります。

MariaDB [django_city]> show columns from city_city;
+------------+-------------+------+-----+---------+----------------+
| Field      | Type        | Null | Key | Default | Extra          |
+------------+-------------+------+-----+---------+----------------+
| id         | int(11)     | NO   | PRI | NULL    | auto_increment |
| key        | varchar(10) | NO   |     | NULL    |                |
| name       | varchar(20) | NO   |     | NULL    |                |
| population | int(11)     | NO   |     | NULL    |                |
| date_mod   | date        | NO   |     | NULL    |                |
+------------+-------------+------+-----+---------+----------------+

primary_key=True を設定すると、そのコラムが プライマリーキーになり、 id は生成されなくなります。
次のように設定します。

models.py
# ------------------------------------------------------------------
#
#	models.py
#
#					Feb/17/2019
# ------------------------------------------------------------------
from django.db import models

class City(models.Model):
	key = models.CharField(max_length=10,primary_key=True)
	name = models.CharField(max_length=20)
	population = models.IntegerField(default=0)
	date_mod = models.DateField()

	def __str__(self):
		return '<City: ' + \
			self.key + ', ' + self.name + '>'
# ------------------------------------------------------------------

これで出来るテーブルは次のようになります。

MariaDB [django_city]> show columns from city_city;
+------------+-------------+------+-----+---------+-------+
| Field      | Type        | Null | Key | Default | Extra |
+------------+-------------+------+-----+---------+-------+
| key        | varchar(10) | NO   | PRI | NULL    |       |
| name       | varchar(20) | NO   |     | NULL    |       |
| population | int(11)     | NO   |     | NULL    |       |
| date_mod   | date        | NO   |     | NULL    |       |
+------------+-------------+------+-----+---------+-------+

参考
モデルフィールドリファレンス

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?