フィールドオプション
以下の引数は全てのフィールドタイプで有効です。全て省略可能です。
null
-
Field.null
True``の場合、Django はデータベース内に ``NULL として空の値を保持します。デフォルトは False です。
空の文字列値は常に NULL ではなく空の文字列として保持されるため、文字列ベースのフィールド (CharField や TextField) で null を使うことは避けてください。文字列ベースのフィールドが null=True を持つ場合、”データなし” に対する 2 種類の値があり得ます: NULL と空の文字列です。ほとんどの場合、”データなし” に対して 2 種類の値を持つのは無駄なことです; Django の慣習では、NULL ではなく空の文字列を使います。
文字列ベースと非文字列ベースのフィールドのどちらでも、フォーム内で空の値を許容したい場合には、blank=True をセットすることも必要となります。これは、null パラメータはデータベーストレー時のみに影響するためです (blank を参照してください)。
注釈
Oracleのデータベースバックエンドを使っているときには、この属性にかかわらず、値 NULL が空の文字列を意味するために保持されます。
BooleanField で null 値を許容したい場合、代わりに NullBooleanField を使ってください。
blank
-
Field.blank
True の場合、フィールドはブランクになることが許容されます。デフォルトは False です。
null とは異なる点に注意してください。null が純粋にデータベースに関連する一方で、blank はバリデーションに関連します。フィールドが blank=True を持つ場合、フォームバリデーションは空の値のエントリーを許容します。blank=False を持つ場合、フィールドは必須となります。
choices
-
Field.choices
フィールドに対する選択肢として使うための 2 項目の iterable 自体で構成される ([(A, B), (A, B) ...]) iterable (例: リストやタプル) です。これが与えられた場合は、デフォルトのフォームウィジェットは、標準のテキストフィールドの代わりに、選択肢を伴ったセレクトボックスになります。
各タプルの最初の要素は、モデル上でセットするための実際の値です。2 番目の要素は人間が読むための名前です。例えば:
YEAR_IN_SCHOOL_CHOICES = (
('FR', 'Freshman'),
('SO', 'Sophomore'),
('JR', 'Junior'),
('SR', 'Senior'),
)
一般的に、モデルクラスの内部で選択肢を定義し、それぞれの値に適切に名前づけられた定数を定義するのがベストです:
from django.db import models
class Student(models.Model):
FRESHMAN = 'FR'
SOPHOMORE = 'SO'
JUNIOR = 'JR'
SENIOR = 'SR'
YEAR_IN_SCHOOL_CHOICES = (
(FRESHMAN, 'Freshman'),
(SOPHOMORE, 'Sophomore'),
(JUNIOR, 'Junior'),
(SENIOR, 'Senior'),
)
year_in_school = models.CharField(
max_length=2,
choices=YEAR_IN_SCHOOL_CHOICES,
default=FRESHMAN,
)
def is_upperclass(self):
return self.year_in_school in (self.JUNIOR, self.SENIOR)
モデルクラスの外部で選択肢のリストを定義して参照することもできますが、モデルの内部でそれぞれの選択肢の値と名前を定義することは、全ての情報をクラスとともに維持し、選択肢を参照しやすくします (例: Student.SOPHOMORE は、Student モデルがインポートされたあらゆる場所で使うことができます)。
組織化する目的に使用できる、名前付きグループに利用可能な選択肢を収集することもできます。
MEDIA_CHOICES = (
('Audio', (
('vinyl', 'Vinyl'),
('cd', 'CD'),
)
),
('Video', (
('vhs', 'VHS Tape'),
('dvd', 'DVD'),
)
),
('unknown', 'Unknown'),
)
各タプルの最初の要素はグループに適用するための名前です。2 番目の要素は 2- タプルの iterale です。値とオプションのための人間が読むための名前を含んだ 各 2- タプルを伴います。グループ化されたオプションは、1 つのリストの中でグループ化されていないオプションと結合することができます (例えば、この例の unknown オプションです)。
choices がセットされているモデルフィールドごとに、Django はフィールドの現在の値に対して人間が読める名前を取得するメソッドを追加します。データベース API ドキュメントの get_FOO_display() を参照してください。
選択肢はどんな iterable オブジェクトも取り得る – 必ずしもリストやタプルではない – ことに注意してください。これにより、選択肢を動的に構成することができます。しかし、choices を動的にするためいろいろと工夫するぐらいなら、ForeignKey を使って適切なデータベーステーブルを使用する方が良いでしょう。 choices は、ごく稀にしか変化しない静的なデータを意味しています。
blank=False が default とともにフィールド上にセットされない限り、"---------" を含むラベルがセレクトボックスに表示されます。この動作をオーバーライドするためには、None を含む choices にタプルを追加してください; 例えば (None, '表示専用の文字列'). もしくは、None の代わりに空の文字列を使うこともできます。これは特に CharField などに適しています。
db_column
-
Field.db_column
The name of the database column to use for this field. If this isn’t given,
Django will use the field’s name.
If your database column name is an SQL reserved word, or contains
characters that aren’t allowed in Python variable names – notably, the
hyphen – that’s OK. Django quotes column and table names behind the
scenes.
db_index
-
Field.db_index
True の場合、データベースインデックスがこのフィールドのために生成されます。
db_tablespace
-
Field.db_tablespace
The name of the database tablespace to use for
this field’s index, if this field is indexed. The default is the project’s
DEFAULT_INDEX_TABLESPACE setting, if set, or the
db_tablespace of the model, if any. If the backend doesn’t
support tablespaces for indexes, this option is ignored.
default
-
Field.default
そのフィールドのデフォルト値です。このオプションには特定の値もしくは呼び出し可能オブジェクトを渡すことができます。もし渡した値が呼び出し可能であれば新しくオブジェクトが生成される度に呼び出されます。
The default can’t be a mutable object (model instance, list, set, etc.),
as a reference to the same instance of that object would be used as the default
value in all new model instances. Instead, wrap the desired default in a
callable. For example, if you want to specify a default dict for
JSONField, use a function:
def contact_default():
return {"email": "to1@example.com"}
contact_info = JSONField("ContactInfo", default=contact_default)
lambdas can’t be used for field options like default because they
can’t be serialized by migrations. See that
documentation for other caveats.
For fields like ForeignKey that map to model instances, defaults
should be the value of the field they reference (pk unless
to_field is set) instead of model instances.
The default value is used when new model instances are created and a value
isn’t provided for the field. When the field is a primary key, the default is
also used when the field is set to None.
editable
-
Field.editable
If False, the field will not be displayed in the admin or any other
ModelForm. They are also skipped during model
validation. Default is True.
error_messages
-
Field.error_messages
The error_messages argument lets you override the default messages that the
field will raise. Pass in a dictionary with keys matching the error messages you
want to override.
Error message keys include null, blank, invalid, invalid_choice,
unique, and unique_for_date. Additional error message keys are
specified for each field in the Field types section below.
help_text
-
Field.help_text
フォームウィジェットと共に表示される “補助” テキストになります。この値はフィールドがフォームとして利用されない場合でもドキュメント化する際に有用です。
Note that this value is not HTML-escaped in automatically-generated
forms. This lets you include HTML in help_text if you so
desire. For example:
help_text="Please use the following format: <em>YYYY-MM-DD</em>."
Alternatively you can use plain text and
django.utils.html.escape() to escape any HTML special characters. Ensure
that you escape any help text that may come from untrusted users to avoid a
cross-site scripting attack.
primary_key
-
Field.primary_key
True の場合、設定したフィールドはそのモデルの主キーとなります。
If you don’t specify primary_key=True for any field in your model, Django
will automatically add an AutoField to hold the primary key, so you
don’t need to set primary_key=True on any of your fields unless you want to
override the default primary-key behavior. For more, see
Automatic primary key fields.
primary_key=True implies null=False and
unique=True. Only one primary key is allowed on an
object.
The primary key field is read-only. If you change the value of the primary
key on an existing object and then save it, a new object will be created
alongside the old one.
unique
-
Field.unique
True の場合、そのフィールドはテーブル上で一意となる制約を受けます。
This is enforced at the database level and by model validation. If
you try to save a model with a duplicate value in a unique
field, a django.db.IntegrityError will be raised by the model’s
save() method.
This option is valid on all field types except ManyToManyField,
OneToOneField, and FileField.
Note that when unique is True, you don’t need to specify
db_index, because unique implies the creation of an index.
unique_for_date
-
Field.unique_for_date
Set this to the name of a DateField or DateTimeField to
require that this field be unique for the value of the date field.
For example, if you have a field title that has
unique_for_date="pub_date", then Django wouldn’t allow the entry of two
records with the same title and pub_date.
Note that if you set this to point to a DateTimeField, only the date
portion of the field will be considered. Besides, when USE_TZ is
True, the check will be performed in the current time zone at the time the object gets saved.
This is enforced by Model.validate_unique() during model validation
but not at the database level. If any unique_for_date constraint
involves fields that are not part of a ModelForm (for
example, if one of the fields is listed in exclude or has
editable=False), Model.validate_unique() will
skip validation for that particular constraint.
unique_for_month
-
Field.unique_for_month
Like unique_for_date, but requires the field to be unique with
respect to the month.
verbose_name
-
Field.verbose_name
A human-readable name for the field. If the verbose name isn’t given, Django
will automatically create it using the field’s attribute name, converting
underscores to spaces. See Verbose field names.
validators
-
Field.validators
A list of validators to run for this field. See the validators
documentation for more information.
Registering and fetching lookups
Field implements the lookup registration API.
The API can be used to customize which lookups are available for a field class, and
how lookups are fetched from a field.
フィールドの型
BigAutoField
-
class
BigAutoField(**options)[ソース]
64 ビットの数値です。1 から 9223372036854775807 までの数を扱える以外は、AutoField と同じです。
BigIntegerField
-
class
BigIntegerField(**options)[ソース]
64 ビットの数値です。-9223372036854775808 から 9223372036854775807 を扱える以外は IntegerField と同じです。このフィールドのデフォルトのフォームウィジェットは TextInput です。
BinaryField
-
class
BinaryField(**options)[ソース]
生のバイナリデータを保持するためのフィールドです。bytes` のアサインメントのみをサポートします。このフィールドには機能制限があります。例えば、BinaryField の値でクエリセットをフィルタすることはできません。また、BinaryField を ModelForm に含めることもできません。
BinaryField を誤用する
ファイルをデータベース内に保持したいと考えるかもしれませんが、これは 99% のケースで不適切な設計だということをよく考えてください。このフィールドは適切な static files の処理の代替では ありません.
CharField
-
class
CharField(max_length=None, **options)[ソース]
小 - 大サイズの文字列のフィールドです。
多量のテキストを扱うときは TextField を使ってください。
このフィールドのデフォルトのフォームウィジェットは TextInput です。
CharField には追加的な必須の引数があります:
-
CharField.max_length
フィールドの (文字列の) 最大文字数です。max_length はデータベースレベルと Django のバリデーションで施行されます。
注釈
複数のデータベースバックエンド間で使われるアプリケーションを作る場合は、いくつかのバックエンドで max_length に制限があることに注意しなければなりません。詳しくは database backend notes を参照してください。
MySQL ユーザー
MySQLdb 1.2.2 と utf8_bin の照合 (デフォルトでは ありません) でこのフィールドを使う場合は、いくつか気をつけるべきことがあります。詳しくは MySQL database notes を参照してください。
CommaSeparatedIntegerField
-
class
CommaSeparatedIntegerField(max_length=None, **options)[ソース]
カンマによって区切られた数値のフィールドです。CharField と同じく、max_length 引数が必須で、そこで説明したデータベースの可搬性についての注意を考慮する必要があります。
DateField
-
class
DateField(auto_now=False, auto_now_add=False, **options)[ソース]
Python で datetime.date インスタンスによって表される日付です。多少の追加的な省略可能な引数を持ちます:
-
DateField.auto_now
オブジェクトが保存される度に自動的に現在の日付をセットします。”最後の変更” タイムスタンプに役立ちます。現在の日付が常に使われる点に注意してください; オーバーライドできる単なるデフォルト値ではありません。
Model.save() が呼ばれたとき、フィールドは自動的に更新されるだけです。QuerySet.update() のような別の方法で他のフィールドに更新を加えるとき、フィールドは更新されません。あのように更新の中でフィールドの独自の値を指定できるとしてもです。
-
DateField.auto_now_add
オブジェクトが最初に作成されるとき、自動的にフィールドに現在の日付をセットします。タイムスタンプの作成に役立ちます。現在の日付が 常に 使われる点に注意してください; オーバーライドできる単なるデフォルト値ではありません。たとえオブジェクトを作成するときに値をセットしたとしても無視されます。このフィールドを修正できるようにしておきたい場合は、auto_now_add=True の代わりに以下をセットしてください:
このフィールドのデフォルトのフォームウィジェットは TextInput です。admin は JavaScript カレンダーと “今日” のショートカットを加えます。追加の invalid_date エラーメッセージキーを含みます。
オプション auto_now_add、auto_now、default` は相互に排他的です。これらのオプションを組み合わせるとエラーが発生します。
注釈
現在実装されているように、auto_now や auto_now_add を True にセットすると、フィールドは editable=False と blank=True にセットされます。
注釈
The auto_now and auto_now_add options will always use the date in
the default timezone at the moment of
creation or update. If you need something different, you may want to
consider simply using your own callable default or overriding save()
instead of using auto_now or auto_now_add; or using a
DateTimeField instead of a DateField and deciding how to handle the
conversion from datetime to date at display time.
DateTimeField
-
class
DateTimeField(auto_now=False, auto_now_add=False, **options)[ソース]
Python で datetime.datetime インスタンスによって表される日付と時刻です。DateField と同じくいくつかの追加的な引数を持ちます:
このフィールドのデフォルトのフォームウィジェットは単一の TextInput です。admin は JavaScript ショートカットとともに 2 つの別々の TextInput ウィジェットを使います。
DecimalField
-
class
DecimalField(max_digits=None, decimal_places=None, **options)[ソース]
Python で Decimal インスタンスによって表される固定精度の小数です。2 つの 必須の 引数があります:
-
DecimalField.max_digits
数値内で使える桁数の最大値です。 decimal_places 以上でなければならない点に注意してください。
-
DecimalField.decimal_places
数値とともに保持される小数点以下の位の数です。
例えば、小数点以下第2位の精度で 999 までの数値を保持するためには、以下を指定します:
models.DecimalField(..., max_digits=5, decimal_places=2)
小数点以下第10位の精度で約10億までを保持するには:
models.DecimalField(..., max_digits=19, decimal_places=10)
このフィールドのデフォルトのフォームウィジェットは、localize が False のとき NumberInput で、そうでなければ TextInput となります。
DurationField
-
class
DurationField(**options)[ソース]
時刻の期間を保持するフィールドで、 Python の timedelta によってモデル化されます。PostgreSQL で使われるときに用いられるデータ型は interval で、Oracle でのデータ型は INTERVAL DAY(9) TO SECOND(6)``です。 それ以外では、マイクロ秒の ``bigint が使われます。
注釈
DurationField での演算はほとんどの場合で機能します。ただし、PostgreSQL 以外のデータベースでは、DurationField の値と DateTimeField インスタンス上の演算を比較することは期待通りに機能しません。
FileField
-
class
FileField(upload_to=None, max_length=100, **options)[ソース]
ファイルアップロードのフィールドです。
注釈
primary_key と unique 引数はサポートされておらず、使われると TypeError が発生します。
2 つの省略可能な引数があります:
-
FileField.upload_to
この属性は、アップロードディレクトリとファイル名を設定する方法を提供し、2 つの方法でセットできます。どちらの場合も、値は Storage.save() メソッドに渡されます。
If you specify a string value, it may contain strftime()
formatting, which will be replaced by the date/time of the file upload (so
that uploaded files don’t fill up the given directory). For example:
class MyModel(models.Model):
# file will be uploaded to MEDIA_ROOT/uploads
upload = models.FileField(upload_to='uploads/')
# or...
# file will be saved to MEDIA_ROOT/uploads/2015/01/30
upload = models.FileField(upload_to='uploads/%Y/%m/%d/')
If you are using the default
FileSystemStorage, the string value
will be appended to your MEDIA_ROOT path to form the location on
the local filesystem where uploaded files will be stored. If you are using
a different storage, check that storage’s documentation to see how it
handles upload_to.
upload_to may also be a callable, such as a function. This will be
called to obtain the upload path, including the filename. This callable must
accept two arguments and return a Unix-style path (with forward slashes)
to be passed along to the storage system. The two arguments are:
| Argument |
説明
|
instance |
An instance of the model where the
FileField is defined. More specifically,
this is the particular instance where the
current file is being attached.
In most cases, this object will not have been
saved to the database yet, so if it uses the
default AutoField, it might not yet have a
value for its primary key field.
|
filename |
The filename that was originally given to the
file. This may or may not be taken into account
when determining the final destination path. |
For example:
def user_directory_path(instance, filename):
# file will be uploaded to MEDIA_ROOT/user_<id>/<filename>
return 'user_{0}/{1}'.format(instance.user.id, filename)
class MyModel(models.Model):
upload = models.FileField(upload_to=user_directory_path)
-
FileField.storage
A storage object, which handles the storage and retrieval of your
files. See Managing files for details on how to provide this object.
このフィールドのデフォルトのフォームウィジェットは ClearableFileInput です。
モデル内で a FileField や ImageField (後述) 使うにはいくつかのステップを取ります:
設定ファイル内で MEDIA_ROOT を指定します。この値は、Django がアップロードされたファイルを置く場所にします (パフォーマン ス上の理由から、ファイルをデータベースに置くことはありません)。 MEDIA_URL をそのディレクトリの公開 URL にします。ディレク トリは Web サーバのユーザアカウントに対して書き込み可能にしておかねばなりません。
- Add the
FileField or ImageField to your model, defining
the upload_to option to specify a subdirectory of
MEDIA_ROOT to use for uploaded files.
- All that will be stored in your database is a path to the file
(relative to
MEDIA_ROOT). You’ll most likely want to use the
convenience url attribute
provided by Django. For example, if your ImageField is called
mug_shot, you can get the absolute path to your image in a template with
{{ object.mug_shot.url }}.
For example, say your MEDIA_ROOT is set to '/home/media', and
upload_to is set to 'photos/%Y/%m/%d'. The '%Y/%m/%d'
part of upload_to is strftime() formatting;
'%Y' is the four-digit year, '%m' is the two-digit month and '%d' is
the two-digit day. If you upload a file on Jan. 15, 2007, it will be saved in
the directory /home/media/photos/2007/01/15.
If you wanted to retrieve the uploaded file’s on-disk filename, or the file’s
size, you could use the name and
size attributes respectively; for more
information on the available attributes and methods, see the
File class reference and the Managing files
topic guide.
注釈
The file is saved as part of saving the model in the database, so the actual
file name used on disk cannot be relied on until after the model has been
saved.
The uploaded file’s relative URL can be obtained using the
url attribute. Internally,
this calls the url() method of the
underlying Storage class.
Note that whenever you deal with uploaded files, you should pay close attention
to where you’re uploading them and what type of files they are, to avoid
security holes. Validate all uploaded files so that you’re sure the files are
what you think they are. For example, if you blindly let somebody upload files,
without validation, to a directory that’s within your Web server’s document
root, then somebody could upload a CGI or PHP script and execute that script by
visiting its URL on your site. Don’t allow that.
Also note that even an uploaded HTML file, since it can be executed by the
browser (though not by the server), can pose security threats that are
equivalent to XSS or CSRF attacks.
FileField instances are created in your database as varchar
columns with a default max length of 100 characters. As with other fields, you
can change the maximum length using the max_length argument.
FileField と FieldFile
-
class
FieldFile[ソース]
モデル上の FileField にアクセスするとき、元となるファイルにアアクセスするためのプロキシとして、FieldFile のインスタンスが与えられます。
FieldFile の API は File の API を反映していますが、主な違いが 1 つあります: クラスによってラップされたオブジェクトは必ずしも Python のビルトインのファイルオブジェクトのラッパーであるとは限りません。 代わりに、Storage.open() メソッドの結果を包むラッパーで、これは File オブジェクトもしくは File API の独自ストレージの実装となります。
class:~django.core.files.File から継承する API (read() や write()) に加えて、FieldFile 元となるファイルと相互にやりとりするための複数のメソッドを含んでいます:
警告
このクラスの 2 つのメソッド、save() と delete() は、デフォルトで、関連する FieldFile のモデルオブジェクトをデータベースに保存します。
-
FieldFile.name
関連する FileField の Storage のルートからの相対パスを含むファイル名です。
-
FieldFile.size
元となる Storage.size() メソッドの結果です。
-
FieldFile.url
元となる Storage クラス の url() メソッドを呼ぶことによって、ファイルの相対 URL にアクセスするための読み取り専用プロパティです。
-
FieldFile.open(mode='rb')[ソース]
このインスタンスに関連付けられたファイルを、指定された モード で開くか、開き直します。標準の Python の open() メソッドとは違い、ファイルのデスクリプタを返しません。
元となるファイルはアクセスするときに暗黙的に開かれるので、元となるファイルにポインタをリセットするためか モード を変更するため以外には、このメソッドを呼ぶ必要はないでしょう。
-
FieldFile.close()[ソース]
標準の Python の file.close() メソッドのように動作し、このインスタンスに関連付けられたファイルを閉じます。
-
FieldFile.save(name, content, save=True)[ソース]
このメソッドは、ファイル名とファイルの内容を取り、それらをフィールドのストレージクラスに渡し、格納されたファイルをモデルフィールドに関連付けます。 手動でファイルデータをモデル上の FileField インスタンスに関連付けるには、save() メソッドを使用してそのファイルデータを保持します。
2 つの必要な引数をとります: name はファイルの名前で、content はファイルの内容を含むオブジェクトです。 省略可能な save 引数は、このフィールドに関連付けられたファイルが変更された後にモデルインスタンスが保存されるかどうかをコントロールします。 デフォルトは True です。
content 引数は、Python のビルトインのファイルオブジェクトではなく、django.core.files.File のインスタンスでなければならないことに注意してください。 以下のように、既存の Python ファイルオブジェクトから File を構築することができます:
from django.core.files import File
# Open an existing file using Python's built-in open()
f = open('/path/to/hello.world')
myfile = File(f)
もしくは、以下のように Python の文字列から構築することもできます:
from django.core.files.base import ContentFile
myfile = ContentFile("hello world")
より詳しくは Managing files をご覧ください。
-
FieldFile.delete(save=True)[ソース]
このインスタンスに関連付けられているファイルを削除し、フィールドのすべての属性をクリアします。 注: このメソッドは、delete() が呼び出されたときにファイルが開いた場合、ファイルを閉じます。
省略可能な save 引数は、このフィールドに関連付けられたファイルが削除された後にモデルインスタンスを保存するかどうかをコントロールします。 デフォルトは True です。
モデルを削除するとき、関連ファイルは削除されない点に注意してください。 孤立したファイルをクリーンアップする必要がある場合、自分で処理する必要があります (例えば、手動で実行したり、例えば cron などを通して定期的に実行される、独自の管理コマンドです)。
FilePathField
-
class
FilePathField(path=None, match=None, recursive=False, max_length=100, **options)[ソース]
ファイルシステム上の特定のディレクトリ内のファイル名に選択肢が制限されている CharField です。3 つの特別な引数があり、最初の 1 つは 必須 です:
-
FilePathField.path
必須です。FilePathField が選択肢から取得するディレクトリへの、ファイルシステムの絶対パスです。例: "/home/images"。
-
FilePathField.match
省略可能です。正規表現で、文字列として、FilePathField がファイル名をフィルタリングするために使用します。 正規表現は、フルパスではなくベースファイル名に適用される点に注意してください。 例: "foo.*\.txt$"。これは foo23.txt とは合致しますが、bar.txt や foo23.png とは合致しません。
-
FilePathField.recursive
省略可能です。True か False のどちらかを取り、デフォルトは False です。path の全てのサブディレクトリを含むかどうかを指定します。
-
FilePathField.allow_files
省略可能です。True か False を取り、デフォルトは True です。指定された場所にあるファイルを含むかどうかを指定します。 これか allow_folders のどちらかを True にする必要があります。
-
FilePathField.allow_folders
省略可能です。True か False を取り、デフォルトは False です。指定した場所にあるフォルダーを含むかどうかを指定します。これか allow_files のどちらかを True にする必要があります。
もちろん、これらの引数は同時に使うことができます。
1つの可能性は、フルパスではなく、ベースファイル名に match が適用されることです。 したがって、この例:
FilePathField(path="/home/images", match="foo.*", recursive=True)
...は、/home/images/foo/bar.png ではなく /home/images/foo.png とマッチします。これは、match がベースのファイル名に適用されるからです (foo.png と bar.png)。
FilePathField のインスタンスは、デフォルトが最大 100 文字の varchar カラムとして、データベース上に生成されます。他のフィールドと同様に、max_length 引数を使って最大文字数を変更することができます。
FloatField
-
class
FloatField(**options)[ソース]
float インスタンスによって表される Python の浮動小数点数です。
このフィールドのデフォルトのフォームウィジェットは、localize が False のとき NumberInput で、そうでなければ TextInput となります。
FloatField と DecimalField の比較
FloatField クラスは、DecimalField クラスと混同されることがあります。両方とも実数を表しますが、異なる方法で表現しています。FloatField は内部的には Python の float 型を使い、DecimalField は Python の Decimal 型を使います。この 2 つの違いについては、 Python のドキュメント decimal module を参照してください。
ImageField
-
class
ImageField(upload_to=None, height_field=None, width_field=None, max_length=100, **options)[ソース]
FileField から全ての属性とメソッドを継承して、さらにアップロードされたオブジェクトが有効な画像であることを検証します。
FileField で使える専用の属性に加えて、ImageField には height と width 属性があります。
これらの属性の照会を容易にするために、ImageField には 2 つの追加的な省略可能な引数があります:
-
ImageField.height_field
モデルインスタンスが保存される度に画像の高さで自動入力される、モデルフィールドの名前です。
-
ImageField.width_field
モデルインスタンスが保存される度に画像の幅で自動入力される、モデルフィールドの名前です。
Pillow ライブラリを必要とします。
ImageField のインスタンスは、デフォルトが最大 100 文字の varchar カラムとして、データベース上に生成されます。他のフィールドと同様に、max_length 引数を使って最大文字数を変更することができます。
このフィールドのデフォルトのフォームウィジェットは ClearableFileInput です。
IntegerField
-
class
IntegerField(**options)[ソース]
数値です。-2147483648 から 2147483647 までの値は、Django でサポートされているデータベース内では安全です。このフィールドのデフォルトのフォームウィジェットは、localize が False のときには NumberInput で、そうでなければ TextInput となります。
GenericIPAddressField
-
class
GenericIPAddressField(protocol='both', unpack_ipv4=False, **options)[ソース]
IPv4 か IPv6 のアドレスで、文字列フォーマットです (例: 192.0.2.30 ないし 2a02:42fe::4)。このフィールドのデフォルトのフォームウィジェットは TextInput です。
IPv6 アドレスは、 RFC 4291#section-2.2 section 2.2 (同セクションの paragraph 3 で提案された IPv4 のフォーマットの使用を含む) にしたがって、 ::ffff:192.0.2.0 のように正規化します。たとえば、 2001:0::0:01 は 2001::1 と正規化され、 ::ffff:0a0a:0a0a は ::ffff:10.10.10.10 と正規化されます。そして、すべての文字は小文字に変換されます。
-
GenericIPAddressField.protocol
有効なインプットを、指定したプロトコルに制限します。 使用可能な値は 'both' (デフォルト)、'IPv4'、'IPv6' のどれかです。マッチングは大文字と小文字を区別しません。
-
GenericIPAddressField.unpack_ipv4
IPv4 にマッピングされた ::ffff:192.0.2.1 のようなアドレスをアンパックします。このオプションを有効にすると、このアドレスは 192.0.2.1 とアンパックされます。デフォルトは無効です。protocol が 'both' に設定されている場合にだけ使用できます。
ブランク値を要する場合、ブランク値は null として保持されるため、null 値を許容する必要があります。
PositiveIntegerField
-
class
PositiveIntegerField(**options)[ソース]
IntegerField とほぼ同じですが、正の値かゼロ (0) でなければなりません。Django によってサポートされる全てのデータベースで、0 から 2147483647 までの値は安全です。後方互換性の理由から、値 0 が有効となっています。
PositiveSmallIntegerField
-
class
PositiveSmallIntegerField(**options)[ソース]
PositiveIntegerField とほぼ同じですが、特定の (データベースに依存した) ポイントより下の値のみを許容します。Django でサポートされている全てのデータベースで、0 から 32767 までの値は安全です。
SlugField
-
class
SlugField(max_length=50, **options)[ソース]
Slug は新聞の用語です。 スラグは、文字、数字、アンダースコア、またはハイフンのみを含む短いラベルです。 一般的に URL 内で使用されます。
CharField のように、max_length を指定することもできます (データベースの可搬性についてのノートとそのセクションの max_length も参照してください)。max_length が指定されていないとき、Django はデフォルトの文字数 50 を使います。
暗黙的に Field.db_index を True にセットします。
It is often useful to automatically prepopulate a SlugField based on the value
of some other value. You can do this automatically in the admin using
prepopulated_fields.
-
SlugField.allow_unicode
If True, the field accepts Unicode letters in addition to ASCII
letters. Defaults to False.
SmallIntegerField
-
class
SmallIntegerField(**options)[ソース]
IntegerField とほぼ同じですが、特定の (データベースに依存した) ポイントより下の値のみを許容します。Django でサポートされている全てのデータベースで、-32768 から 32767 までの値は安全です。
TextField
-
class
TextField(**options)[ソース]
多量のテキストのフィールドです。このフィールドのデフォルトのフォームウィジェットは Textarea です。
max_length 属性を指定した場合、自動生成されたフォームフィールドの Textarea ウィジェット内で反映されます。ただし、モデルやデータベースのレベルでは施行されません。そのためには CharField を使用してください。
MySQL ユーザー
このフィールドを MySQLdb 1.2.1p2 と utf8_bin の照合 (デフォルトでは ありません) で使う場合、いくつか注意すべき点があります。詳しくは MySQL database notes を参照してください。
TimeField
-
class
TimeField(auto_now=False, auto_now_add=False, **options)[ソース]
Python で datetime.time インスタンスによって表される時刻です。DateField と同じ自動入力されるオプションを受け入れます。
このフィールドのデフォルトのフォームウィジェットは TextInput です。admin がいくつかの JavaScript ショートカットを加えます.
UUIDField
-
class
UUIDField(**options)[ソース]
UUID (Universally Unique Identifier) を保持するためのフィールドです。Python’s UUID クラスを使います。 PostgreSQL 上で使われるとき、uuid データ型の中に保持します。それ以外は char(32) の中に保持します。
UUID は attr:~Field.primary_key に代わる AutoField への良い選択肢です。 データベースはあなたのための UUID を生成しないため、default を使うことが推奨されます:
import uuid
from django.db import models
class MyUUIDModel(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
# other fields
Callable (括弧が省略されている場合) は UUID のインスタンスではなく、default に渡されます。