LoginSignup
93
95

More than 1 year has passed since last update.

Django 4.0 のモデルフィールドリファレンスまとめ

Last updated at Posted at 2018-09-27

Django 4.0 のモデルフィールドリファレンスを、まとめました。
※分かりやすくするために、文章を編集したり、例文を追加している箇所があります

モデルフィールドのオプションの関係は、以下の通りです。

models.py
class Book(models.Model):
    # ... = models.フィールドの型(オプション)
    title = models.CharField(max_length=255)
    price = models.IntegerField(null=True, blank=True)

フィールドの型 (基本)

よく使うフィールドの型として、以下があります。

区分 フィールドの型 説明 SQLiteの型 MySQLの型
整数 IntegerField 整数のフィールドです。 integer int
BigIntegerField 64 ビット化した IntegerField (整数)です。 bigint bigint
小数 FloatField 浮動小数点数のフィールドです。 real double
DecimalField 固定精度10進数の少数です。 decimal decimal
文字 CharField 小~大サイズの文字列のフィールドです。 varchar varchar
TextField 多量のテキストのフィールドです。 text longtext
真偽 BooleanField true/false のフィールドです。 bool tinyint(1)
日付 DateField 日付のフィールドです。 date date
TimeField 時刻のフィールドです。 time time(6)
DateTimeField 日時 (日付 + 時刻) のフィールドです。 datetime datetime(6)

※SQLiteとMySQLのカラムの型は、SQLite3 と MySQL8 を使った場合の対応表です。

フィールドの型 (その他)

その他のフィールドの型として、以下があります。

区分 フィールドの型 説明 SQLiteの型 MySQLの型
整数 SmallIntegerField -32768 〜 32767 の IntegerField (整数)です。 smallint smallint
PositiveSmallIntegerField 0 〜 32767 の IntegerField (整数)です。 smallint unsigned smallint unsigned
PositiveIntegerField 0 〜 2147483647 の IntegerField (整数)です。 integer unsigned int unsigned
PositiveBigIntegerField 0 〜 9223372036854775807 の IntegerField (整数)です。 bigint unsigned bigint unsigned
文字 URLField URLのための CharField (文字列)です。 varchar(200) varchar(200)
EmailField 有効な電子メールアドレスかチェックする CharField (文字列)です。 varchar(254) varchar(254)
JSONField JSONでエンコードされたデータを格納するためのフィールドです。 text json
SlugField Slug は新聞の用語です。
スラッグは、半角の英数字、アンダースコア、
またはハイフンのみを含む短いラベルです。
一般的に URL 内で使用されます。
varchar(50) varchar(50)
FilePathField ファイルシステム上の特定のディレクトリ内のファイル名に
選択肢が制限されている CharField (文字列)です。
varchar(100) varchar(100)
GenericIPAddressField Pv4 か IPv6 のアドレスで、文字列フォーマットです。 char(39) char(39)
日付 DurationField 時刻の期間を保持するフィールドで、
Python の timedelta によってモデル化されます。
bigint bigint
バイナリ BinaryField 生のバイナリデータを格納するフィールドです。 BLOB longblob
アップロード FileField ファイルアップロードのフィールドです。 varchar(100) varchar(100)
ImageField FileField から全ての属性とメソッドを継承して、
さらにアップロードされたオブジェクトが有効な画像であることを検証します。
varchar(100) varchar(100)
連番 SmallAutoField 1 〜 32767 の AutoField です。 integer smallint
AutoField 自動的にインクリメントする IntegerField (整数)です。 integer int
BigAutoField 64 ビット化した AutoField です。 integer bigint
UUIDField UUID (Universally Unique Identifier) を保持するためのフィールドです。
Python's UUID クラスを使います。
char(32) char(32)

リレーションシップフィールド

リレーションシップフィールドの型として、以下があります。

区分 フィールドの型 説明
関係 OneToOneField 1対1の関係フィールドです。
ForeignKey 多対1の関係フィールドです。
ManyToManyField 多対多の関係フィールドです。

フィールドオプション(共通)

以下の引数は、全てのフィールドタイプで有効です。全て省略可能です。

区分 オプション 説明
共通 null True の場合、Django はデータベース内に NULL として空の値を保持します。
デフォルトは False です。
blank True の場合、フィールドはブランクになることが許容されます。
デフォルトは False です。
choices このフィールドの選択肢として使用します。
2項目からなる iterable (リストやタプル)を設定します。
例: choices=((1, '男性'), (2, '女性') ...)
db_column このフィールドを使用するためのデータベースのカラムの名前です。
もし与えられなければ、Django はフィールド名を使用します。
db_index True の場合、データベースインデックスがこのフィールドのために生成されます。
db_tablespace このフィールドの索引に使用するデータベース表領域の名前です。
default そのフィールドのデフォルト値です。
editable Falseの場合、フィールドは Admin (管理画面)または他の ModelForm に表示されません。
デフォルトは True です。
error_messages error_messages 引数を使用すると、フィールドが生成するデフォルトのメッセージを上書きできます。
help_text フォームウィジェットと共に表示される "補助" テキストになります。
primary_key True の場合、設定したフィールドはそのモデルの主キーとなります。
unique True の場合、そのフィールドはテーブル上で一意となる制約を受けます。
unique_for_date DateFieldまたはDateTimeFieldの名前を設定すると(関連付けると)、
このフィールドが日付フィールドの値に対して一意であることを要求します。
unique_for_month unique_for_dateと同様ですが、フィールドはその月に関してユニークである必要があります。
unique_for_year unique_for_dateやunique_for_monthと同様です。
verbose_name 人間が読むための(詳細な)フィールド名です。
validators このフィールドで実行するバリデータのリストです。

フィールドオプション(追加)

以下の追加引数は、特定のフィールドタイプで有効です。
DecimalField、CharField、FilePathFieldには必須な引数がありますが、それ以外は省略できます。

models.py
class Product(models.Model):
    # 以下は必須な引数です
    length = models.DecimalField(max_digits=5, decimal_places=2) # 999.99を扱う場合の指定方法
    name = models.CharField(max_length=10)
    file_path = models.FilePathField(path='/media/photos')

以下は、よく使うフィールドの追加オプションです。

フィールドの型 オプション 説明
DecimalField max_digits (必須) 数値内で使える桁数の最大値です。
decimal_places 以上を設定します。
decimal_places (必須) 小数点以下の位の数です。
CharField max_length (必須) フィールドの最大長(文字数)です。
db_collation フィールドのデータベース照合順序です。
TextField max_length フィールドの最大長(文字数)です。
db_collation フィールドのデータベース照合順序です。
DateField auto_now オブジェクトが保存される度に自動的に現在の日付をセットします。
auto_now_add オブジェクトが最初に作成されるとき、
自動的にフィールドに現在の日付をセットします。

※auto_now と auto_now_add と default は排他的です。
同時に使用するとエラーが発生します。
TimeField auto_now 同上
auto_now_add 同上
DateTimeField auto_now 同上
auto_now_add 同上

以下は、その他のフィールドの追加オプションです。

フィールドの型 オプション 説明
URLField max_length フィールドの最大長(文字数)です。
指定しない場合、デフォルトでmax_length=200が設定されます。
EmailField max_length フィールドの最大長(文字数)です。
指定しない場合、デフォルトでmax_length=254が設定されます。
JSONField encoder 標準の JSON シリアライザーがサポートしていないデータ型をシリアライズします。
デフォルトは json.JSONEncoder です
decoder データベースから取得した値をデシリアライズします。
デフォルトは json.JSONDecoder です。
SlugField max_length フィールドの最大長(文字数)です。
指定しない場合、デフォルトでmax_length=50が設定されます。
allow_unicode True の場合、ASCII文字に加えてUnicode文字を受け入れます。
デフォルトは False です。
FilePathField path (必須) ファイルシステムの絶対パスです。
例: '/home/images'
match 正規表現で、ファイル名をフィルタリングするために使用します。
例: 'foo.*.txt$'
recursive True の場合、path の全てのサブディレクトリを含みます。
デフォルトは False です。
allow_files 指定した場所にあるファイルを含むかどうかを指定します。
デフォルトは True です。
allow_folders 指定した場所にあるフォルダーを含むかどうかを指定します。
デフォルトは False です。

例えば、フォルダのみを含めたい場合
FilePathField(allow_folders=True, allow_files=False) と設定します。
※allow_folders か allow_files のどちらかは True にする必要があります。
max_length フィールドの最大長(文字数)です。
指定しない場合、デフォルトでmax_length=100が設定されます。
GenericIPAddressField protocol 有効なインプットを、指定したプロトコルに制限します。
使用可能な値は 'both' (デフォルト)、'IPv4'、'IPv6' のどれかです。
unpack_ipv4 IPv4 にマッピングされた ::ffff:192.0.2.1 のようなアドレスをアンパックします。
デフォルトは False です。
BinaryField max_length フィールドの最大長(バイト単位)です。
FileField upload_to アップロードディレクトリとファイル名を指定できます。
max_length フィールド(ディレクトリ+ファイル名)の最大長です。
指定しない場合、デフォルトでmax_length=100が設定されます。
storage ファイルの格納と取り出しを処理する記憶オブジェクトです。

以下のように使用できます。
fs = FileSystemStorage(location='/media/photos')
file = models.FileField(storage=fs)
ImageField upload_to アップロードディレクトリとファイル名を指定できます。
height_field モデルインスタンスが保存される度に画像の高さで自動入力される、
モデルフィールドの名前です。
width_field モデルインスタンスが保存される度に画像の幅で自動入力される、
モデルフィールドの名前です。

例えば、以下のようにすると画像がアップロードされる度に
高さと幅が自動保存されます。
image_height = models.PositiveIntegerField(editable=False)
image_width = models.PositiveIntegerField(editable=False)
image_file = models.ImageField(height_field='image_height', width_field='image_width')
max_length フィールド(ディレクトリ+ファイル名)の最大長です。
指定しない場合、デフォルトでmax_length=100が設定されます。

フィールドのデフォルトウィジェット

最後に、フィールドに紐づけられている HTML ウィジット(部品)を表示してみます。

admin.pyにモデルを追加すると、管理画面で参照できるようになります。
今回は、以下のようなサンプルコードを追加しました。

admin.py
admin.site.register(BasicModel)
admin.site.register(OtherModel)
models.py
class BasicModel(models.Model):
    integer_field = models.IntegerField()
    big_integer_field = models.BigIntegerField()
    float_field = models.FloatField()
    decimal_field = models.DecimalField(max_digits=5, decimal_places=2)
    char_field = models.CharField(max_length=10)
    text_field = models.TextField()
    boolean_field = models.BooleanField()
    boolean_field_null_true = models.BooleanField(null=True)
    date_field = models.DateField()
    time_field = models.TimeField()
    date_time_field = models.DateTimeField()


class OtherModel(models.Model):
    small_integer_field = models.SmallIntegerField()
    positive_small_integer_field = models.PositiveSmallIntegerField()
    positive_integer_field = models.PositiveIntegerField()
    positive_big_integer_field = models.PositiveBigIntegerField()
    url_field = models.URLField()
    email_field = models.EmailField()
    json_field = models.JSONField()
    slug_field = models.SlugField()
    file_path_field = models.FilePathField(path='/media/photos')
    generic_ip_address_field = models.GenericIPAddressField()
    duration_field = models.DurationField()
    file_field = models.FileField()
    image_field = models.ImageField()

管理画面で参照すると、以下のような値を入力できるようになります。
1.png
2.png

93
95
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
93
95