モデルフィールドリファレンスLink to this heading
このドキュメントには、Django が提供する field options と field types を含む、Field の全ての API リファレンスが記載されています。
フィールドオプションLink to this heading
以下の引数は全てのフィールドタイプで有効です。全て省略可能です。
nullLink to this heading
- Field.nullLink to this definition
True``の場合、Django はデータベース内に ``NULL として空の値を保持します。デフォルトは False です。
Avoid using null on string-based fields such as
CharField and TextField. If a string-based field has
null=True, that means it has two possible values for "no data": NULL,
and the empty string. In most cases, it's redundant to have two possible values
for "no data;" the Django convention is to use the empty string, not
NULL. One exception is when a CharField has both unique=True
and blank=True set. In this situation, null=True is required to avoid
unique constraint violations when saving multiple objects with blank values.
文字列ベースと非文字列ベースのフィールドのどちらでも、フォーム内で空の値を許容したい場合には、blank=True をセットすることも必要となります。これは、null パラメータはデータベーストレー時のみに影響するためです (blank を参照してください)。
blankLink to this heading
- Field.blankLink to this definition
True の場合、フィールドはブランクになることが許容されます。デフォルトは False です。
null とは異なる点に注意してください。null が純粋にデータベースに関連する一方で、blank はバリデーションに関連します。フィールドが blank=True を持つ場合、フォームバリデーションは空の値のエントリーを許容します。blank=False を持つ場合、フィールドは必須となります。
choicesLink to this heading
- Field.choicesLink to this definition
A sequence consisting itself of iterables of exactly two items (e.g.
[(A, B), (A, B) ...]) to use as choices for this field. If choices are
given, they're enforced by model validation and the
default form widget will be a select box with these choices instead of the
standard text field.
各タプルの最初の要素は、モデル上でセットするための実際の値です。2 番目の要素は人間が読むための名前です。例えば:
YEAR_IN_SCHOOL_CHOICES = [
('FR', 'Freshman'),
('SO', 'Sophomore'),
('JR', 'Junior'),
('SR', 'Senior'),
('GR', 'Graduate'),
]
一般的に、モデルクラスの内部で選択肢を定義し、それぞれの値に適切に名前づけられた定数を定義するのがベストです:
from django.db import models
class Student(models.Model):
FRESHMAN = 'FR'
SOPHOMORE = 'SO'
JUNIOR = 'JR'
SENIOR = 'SR'
GRADUATE = 'GR'
YEAR_IN_SCHOOL_CHOICES = [
(FRESHMAN, 'Freshman'),
(SOPHOMORE, 'Sophomore'),
(JUNIOR, 'Junior'),
(SENIOR, 'Senior'),
(GRADUATE, 'Graduate'),
]
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}
Though you can define a choices list outside of a model class and then
refer to it, defining the choices and names for each choice inside the
model class keeps all of that information with the class that uses it,
and helps reference the choices (e.g, Student.SOPHOMORE
will work anywhere that the Student model has been imported).
組織化する目的に使用できる、名前付きグループに利用可能な選択肢を収集することもできます。
MEDIA_CHOICES = [
('Audio', (
('vinyl', 'Vinyl'),
('cd', 'CD'),
)
),
('Video', (
('vhs', 'VHS Tape'),
('dvd', 'DVD'),
)
),
('unknown', 'Unknown'),
]
The first element in each tuple is the name to apply to the group. The
second element is an iterable of 2-tuples, with each 2-tuple containing
a value and a human-readable name for an option. Grouped options may be
combined with ungrouped options within a single list (such as the
'unknown' option in this example).
choices がセットされているモデルフィールドごとに、Django はフィールドの現在の値に対して人間が読める名前を取得するメソッドを追加します。データベース API ドキュメントの get_FOO_display() を参照してください。
Note that choices can be any sequence object -- not necessarily a list or
tuple. This lets you construct choices dynamically. But if you find yourself
hacking choices to be dynamic, you're probably better off using
a proper database table with a ForeignKey. choices is
meant for static data that doesn't change much, if ever.
blank=False が default とともにフィールド上にセットされない限り、"---------" を含むラベルがセレクトボックスに表示されます。この動作をオーバーライドするためには、None を含む choices にタプルを追加してください; 例えば (None, '表示専用の文字列'). もしくは、None の代わりに空の文字列を使うこともできます。これは特に CharField などに適しています。
Enumeration typesLink to this heading
In addition, Django provides enumeration types that you can subclass to define choices in a concise way:
from django.utils.translation import gettext_lazy as _
class Student(models.Model):
class YearInSchool(models.TextChoices):
FRESHMAN = 'FR', _('Freshman')
SOPHOMORE = 'SO', _('Sophomore')
JUNIOR = 'JR', _('Junior')
SENIOR = 'SR', _('Senior')
GRADUATE = 'GR', _('Graduate')
year_in_school = models.CharField(
max_length=2,
choices=YearInSchool.choices,
default=YearInSchool.FRESHMAN,
)
def is_upperclass(self):
return self.year_in_school in {
self.YearInSchool.JUNIOR,
self.YearInSchool.SENIOR,
}
These work similar to enum from Python's standard library, but with some
modifications:
Enum member values are a tuple of arguments to use when constructing the concrete data type. Django supports adding an extra string value to the end of this tuple to be used as the human-readable name, or
label. Thelabelcan be a lazy translatable string. Thus, in most cases, the member value will be a(value, label)two-tuple. See below for an example of subclassing choices using a more complex data type. If a tuple is not provided, or the last item is not a (lazy) string, thelabelis automatically generated from the member name.A
.labelproperty is added on values, to return the human-readable name.A number of custom properties are added to the enumeration classes --
.choices,.labels,.values, and.names-- to make it easier to access lists of those separate parts of the enumeration. Use.choicesas a suitable value to pass tochoicesin a field definition.The use of
enum.unique()is enforced to ensure that values cannot be defined multiple times. This is unlikely to be expected in choices for a field.
Note that using YearInSchool.SENIOR, YearInSchool['SENIOR'], or
YearInSchool('SR') to access or lookup enum members work as expected, as do
the .name and .value properties on the members.
If you don't need to have the human-readable names translated, you can have them inferred from the member name (replacing underscores with spaces and using title-case):
>>> class Vehicle(models.TextChoices):
... CAR = 'C'
... TRUCK = 'T'
... JET_SKI = 'J'
...
>>> Vehicle.JET_SKI.label
'Jet Ski'
Since the case where the enum values need to be integers is extremely common,
Django provides an IntegerChoices class. For example:
class Card(models.Model):
class Suit(models.IntegerChoices):
DIAMOND = 1
SPADE = 2
HEART = 3
CLUB = 4
suit = models.IntegerField(choices=Suit.choices)
It is also possible to make use of the Enum Functional API with the caveat that labels are automatically generated as highlighted above:
>>> MedalType = models.TextChoices('MedalType', 'GOLD SILVER BRONZE')
>>> MedalType.choices
[('GOLD', 'Gold'), ('SILVER', 'Silver'), ('BRONZE', 'Bronze')]
>>> Place = models.IntegerChoices('Place', 'FIRST SECOND THIRD')
>>> Place.choices
[(1, 'First'), (2, 'Second'), (3, 'Third')]
If you require support for a concrete data type other than int or str,
you can subclass Choices and the required concrete data type, e.g.
date for use with DateField:
class MoonLandings(datetime.date, models.Choices):
APOLLO_11 = 1969, 7, 20, 'Apollo 11 (Eagle)'
APOLLO_12 = 1969, 11, 19, 'Apollo 12 (Intrepid)'
APOLLO_14 = 1971, 2, 5, 'Apollo 14 (Antares)'
APOLLO_15 = 1971, 7, 30, 'Apollo 15 (Falcon)'
APOLLO_16 = 1972, 4, 21, 'Apollo 16 (Orion)'
APOLLO_17 = 1972, 12, 11, 'Apollo 17 (Challenger)'
There are some additional caveats to be aware of:
Enumeration types do not support named groups.
Because an enumeration with a concrete data type requires all values to match the type, overriding the blank label cannot be achieved by creating a member with a value of
None. Instead, set the__empty__attribute on the class:class Answer(models.IntegerChoices): NO = 0, _('No') YES = 1, _('Yes') __empty__ = _('(Unknown)')
db_columnLink to this heading
- Field.db_columnLink to this definition
このフィールドを使用するためのデータベースのカラムの名前です。もし与えられなければ、Django はフィールド名を使用します。
データベースのカラム名が SQL の予約語だったり、Python の変数名として使用できない文字 (特に多いのがハイフン) が含まれていたとしても大丈夫です。Django はカラムとテーブルの名前を自動的にクオートして処理してくれます。
db_indexLink to this heading
- Field.db_indexLink to this definition
True の場合、データベースインデックスがこのフィールドのために生成されます。
db_tablespaceLink to this heading
- Field.db_tablespaceLink to this definition
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.
defaultLink to this heading
- Field.defaultLink to this definition
そのフィールドのデフォルト値です。このオプションには特定の値もしくは呼び出し可能オブジェクトを渡すことができます。もし渡した値が呼び出し可能であれば新しくオブジェクトが生成される度に呼び出されます。
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.
editableLink to this heading
- Field.editableLink to this definition
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_messagesLink to this heading
- Field.error_messagesLink to this definition
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.
These error messages often don't propagate to forms. See モデルの error_messages のレンダリングを考える.
help_textLink to this heading
- Field.help_textLink to this definition
フォームウィジェットと共に表示される "補助" テキストになります。この値はフィールドがフォームとして利用されない場合でもドキュメント化する際に有用です。
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_keyLink to this heading
- Field.primary_keyLink to this definition
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
自動インクリメントのプライマリーキーフィールド.
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.
uniqueLink to this heading
- Field.uniqueLink to this definition
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 and
OneToOneField.
Note that when unique is True, you don't need to specify
db_index, because unique implies the creation of an index.
unique_for_dateLink to this heading
- Field.unique_for_dateLink to this definition
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_monthLink to this heading
- Field.unique_for_monthLink to this definition
Like unique_for_date, but requires the field to be unique with
respect to the month.
unique_for_yearLink to this heading
- Field.unique_for_yearLink to this definition
Like unique_for_date and unique_for_month.
verbose_nameLink to this heading
- Field.verbose_nameLink to this definition
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.
validatorsLink to this heading
- Field.validatorsLink to this definition
A list of validators to run for this field. See the validators documentation for more information.
Registering and fetching lookupsLink to this heading
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.
フィールドの型Link to this heading
AutoFieldLink to this heading
- class AutoField(**options)Link to this definition
利用可能な ID に応じて、自動的にインクリメントする IntegerField です。通常は直接使う必要はありません; 指定しない場合は、主キーのフィールドが自動的にモデルに追加されます。自動インクリメントのプライマリーキーフィールド も参照してください。
BigAutoFieldLink to this heading
- class BigAutoField(**options)Link to this definition
64 ビットの数値です。1 から 9223372036854775807 までの数を扱える以外は、AutoField と同じです。
BigIntegerFieldLink to this heading
- class BigIntegerField(**options)Link to this definition
A 64-bit integer, much like an IntegerField except that it is
guaranteed to fit numbers from -9223372036854775808 to
9223372036854775807. The default form widget for this field is a
NumberInput.
BinaryFieldLink to this heading
- class BinaryField(max_length=None, **options)Link to this definition
A field to store raw binary data. It can be assigned bytes,
bytearray, or memoryview.
By default, BinaryField sets editable to False, in which
case it can't be included in a ModelForm.
BinaryField has one extra optional argument:
- BinaryField.max_lengthLink to this definition
The maximum length (in characters) of the field. The maximum length is enforced in Django's validation using
MaxLengthValidator.
BooleanFieldLink to this heading
- class BooleanField(**options)Link to this definition
true/false のフィールドです。
The default form widget for this field is CheckboxInput,
or NullBooleanSelect if null=True.
Field.default が定義されていないときの BooleanField のデフォルト値は None です。
CharFieldLink to this heading
- class CharField(max_length=None, **options)Link to this definition
小 - 大サイズの文字列のフィールドです。
多量のテキストを扱うときは TextField を使ってください。
このフィールドのデフォルトのフォームウィジェットは TextInput です。
CharField には追加的な必須の引数があります:
- CharField.max_lengthLink to this definition
The maximum length (in characters) of the field. The max_length is enforced at the database level and in Django's validation using
MaxLengthValidator.
DateFieldLink to this heading
- class DateField(auto_now=False, auto_now_add=False, **options)Link to this definition
Python で datetime.date インスタンスによって表される日付です。多少の追加的な省略可能な引数を持ちます:
- DateField.auto_nowLink to this definition
オブジェクトが保存される度に自動的に現在の日付をセットします。"最後の変更" タイムスタンプに役立ちます。現在の日付が常に使われる点に注意してください; オーバーライドできる単なるデフォルト値ではありません。
Model.save()が呼ばれたとき、フィールドは自動的に更新されるだけです。QuerySet.update()のような別の方法で他のフィールドに更新を加えるとき、フィールドは更新されません。あのように更新の中でフィールドの独自の値を指定できるとしてもです。
- DateField.auto_now_addLink to this definition
オブジェクトが最初に作成されるとき、自動的にフィールドに現在の日付をセットします。タイムスタンプの作成に役立ちます。現在の日付が 常に 使われる点に注意してください; オーバーライドできる単なるデフォルト値ではありません。たとえオブジェクトを作成するときに値をセットしたとしても無視されます。このフィールドを修正できるようにしておきたい場合は、
auto_now_add=Trueの代わりに以下をセットしてください:DateFieldに対して:default=date.today-datetime.date.today()よりDateTimeFieldに対して:default=timezone.now-django.utils.timezone.now()より
The default form widget for this field is a
DateInput. The admin adds a JavaScript calendar,
and a shortcut for "Today". Includes an additional invalid_date error
message key.
オプション auto_now_add、auto_now、default` は相互に排他的です。これらのオプションを組み合わせるとエラーが発生します。
DateTimeFieldLink to this heading
- class DateTimeField(auto_now=False, auto_now_add=False, **options)Link to this definition
Python で datetime.datetime インスタンスによって表される日付と時刻です。DateField と同じくいくつかの追加的な引数を持ちます:
The default form widget for this field is a single
DateTimeInput. The admin uses two separate
TextInput widgets with JavaScript shortcuts.
DecimalFieldLink to this heading
- class DecimalField(max_digits=None, decimal_places=None, **options)Link to this definition
A fixed-precision decimal number, represented in Python by a
Decimal instance. It validates the input using
DecimalValidator.
Has two required arguments:
- DecimalField.max_digitsLink to this definition
数値内で使える桁数の最大値です。
decimal_places以上でなければならない点に注意してください。
- DecimalField.decimal_placesLink to this definition
数値とともに保持される小数点以下の位の数です。
例えば、小数点以下第2位の精度で 999 までの数値を保持するためには、以下を指定します:
models.DecimalField(..., max_digits=5, decimal_places=2)
小数点以下第10位の精度で約10億までを保持するには:
models.DecimalField(..., max_digits=19, decimal_places=10)
このフィールドのデフォルトのフォームウィジェットは、localize が False のとき NumberInput で、そうでなければ TextInput となります。
DurationFieldLink to this heading
- class DurationField(**options)Link to this definition
時刻の期間を保持するフィールドで、 Python の timedelta によってモデル化されます。PostgreSQL で使われるときに用いられるデータ型は interval で、Oracle でのデータ型は INTERVAL DAY(9) TO SECOND(6)``です。 それ以外では、マイクロ秒の ``bigint が使われます。
EmailFieldLink to this heading
- class EmailField(max_length=254, **options)Link to this definition
A CharField that checks that the value is a valid email address using
EmailValidator.
FileFieldLink to this heading
- class FileField(upload_to=None, max_length=100, **options)Link to this definition
ファイルアップロードのフィールドです。
2 つの省略可能な引数があります:
- FileField.upload_toLink to this definition
この属性は、アップロードディレクトリとファイル名を設定する方法を提供し、2 つの方法でセットできます。どちらの場合も、値は
Storage.save()メソッドに渡されます。If you specify a string value or a
Path, it may containstrftime()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 yourMEDIA_ROOTpath 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 handlesupload_to.upload_tomay 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
説明
instanceAn instance of the model where the
FileFieldis 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.filenameThe filename that was originally given to the file. This may or may not be taken into account when determining the final destination path.
例:
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.storageLink to this definition
A storage object, which handles the storage and retrieval of your files. See ファイルの管理 for details on how to provide this object.
このフィールドのデフォルトのフォームウィジェットは ClearableFileInput です。
モデル内で a FileField や ImageField (後述) 使うにはいくつかのステップを取ります:
設定ファイル内で
MEDIA_ROOTを指定します。この値は、Django がアップロードされたファイルを置く場所にします (パフォーマン ス上の理由から、ファイルをデータベースに置くことはありません)。MEDIA_URLをそのディレクトリの公開 URL にします。ディレク トリは Web サーバのユーザアカウントに対して書き込み可能にしておかねばなりません。Add the
FileFieldorImageFieldto your model, defining theupload_tooption to specify a subdirectory ofMEDIA_ROOTto 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 convenienceurlattribute provided by Django. For example, if yourImageFieldis calledmug_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 ファイルの管理
topic guide.
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 と FieldFileLink to this heading
- class FieldFileLink to this definition
モデル上の FileField にアクセスするとき、元となるファイルにアアクセスするためのプロキシとして、FieldFile のインスタンスが与えられます。
FieldFile の API は File の API を反映していますが、主な違いが 1 つあります: クラスによってラップされたオブジェクトは必ずしも Python のビルトインのファイルオブジェクトのラッパーであるとは限りません。 代わりに、Storage.open() メソッドの結果を包むラッパーで、これは File オブジェクトもしくは File API の独自ストレージの実装となります。
In addition to the API inherited from File such as
read() and write(), FieldFile includes several methods that
can be used to interact with the underlying file:
- FieldFile.nameLink to this definition
関連する FileField の Storage のルートからの相対パスを含むファイル名です。
- FieldFile.sizeLink to this definition
元となる Storage.size() メソッドの結果です。
- FieldFile.urlLink to this definition
元となる Storage クラス の url() メソッドを呼ぶことによって、ファイルの相対 URL にアクセスするための読み取り専用プロパティです。
- FieldFile.open(mode='rb')Link to this definition
このインスタンスに関連付けられたファイルを、指定された モード で開くか、開き直します。標準の Python の open() メソッドとは違い、ファイルのデスクリプタを返しません。
元となるファイルはアクセスするときに暗黙的に開かれるので、元となるファイルにポインタをリセットするためか モード を変更するため以外には、このメソッドを呼ぶ必要はないでしょう。
- FieldFile.close()Link to this definition
標準の Python の file.close() メソッドのように動作し、このインスタンスに関連付けられたファイルを閉じます。
- FieldFile.save(name, content, save=True)Link to this definition
このメソッドは、ファイル名とファイルの内容を取り、それらをフィールドのストレージクラスに渡し、格納されたファイルをモデルフィールドに関連付けます。 手動でファイルデータをモデル上の 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")
より詳しくは ファイルの管理 をご覧ください。
- FieldFile.delete(save=True)Link to this definition
このインスタンスに関連付けられているファイルを削除し、フィールドのすべての属性をクリアします。 注: このメソッドは、delete() が呼び出されたときにファイルが開いた場合、ファイルを閉じます。
省略可能な save 引数は、このフィールドに関連付けられたファイルが削除された後にモデルインスタンスを保存するかどうかをコントロールします。 デフォルトは True です。
モデルを削除するとき、関連ファイルは削除されない点に注意してください。 孤立したファイルをクリーンアップする必要がある場合、自分で処理する必要があります (例えば、手動で実行したり、例えば cron などを通して定期的に実行される、独自の管理コマンドです)。
FilePathFieldLink to this heading
- class FilePathField(path='', match=None, recursive=False, allow_files=True, allow_folders=False, max_length=100, **options)Link to this definition
A CharField whose choices are limited to the filenames in a certain
directory on the filesystem. Has some special arguments, of which the first is
required:
- FilePathField.pathLink to this definition
必須です。
FilePathFieldが選択肢から取得するディレクトリへの、ファイルシステムの絶対パスです。例:"/home/images"。pathmay also be a callable, such as a function to dynamically set the path at runtime. Example:import os from django.conf import settings from django.db import models def images_path(): return os.path.join(settings.LOCAL_FILE_DIR, 'images') class MyModel(models.Model): file = models.FilePathField(path=images_path)
- FilePathField.matchLink to this definition
省略可能です。正規表現で、文字列として、
FilePathFieldがファイル名をフィルタリングするために使用します。 正規表現は、フルパスではなくベースファイル名に適用される点に注意してください。 例:"foo.*\.txt$"。これはfoo23.txtとは合致しますが、bar.txtやfoo23.pngとは合致しません。
- FilePathField.recursiveLink to this definition
省略可能です。
TrueかFalseのどちらかを取り、デフォルトはFalseです。pathの全てのサブディレクトリを含むかどうかを指定します。
- FilePathField.allow_filesLink to this definition
省略可能です。
TrueかFalseを取り、デフォルトはTrueです。指定された場所にあるファイルを含むかどうかを指定します。 これかallow_foldersのどちらかをTrueにする必要があります。
- FilePathField.allow_foldersLink to this definition
省略可能です。
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 引数を使って最大文字数を変更することができます。
FloatFieldLink to this heading
- class FloatField(**options)Link to this definition
float インスタンスによって表される Python の浮動小数点数です。
このフィールドのデフォルトのフォームウィジェットは、localize が False のとき NumberInput で、そうでなければ TextInput となります。
ImageFieldLink to this heading
- class ImageField(upload_to=None, height_field=None, width_field=None, max_length=100, **options)Link to this definition
FileField から全ての属性とメソッドを継承して、さらにアップロードされたオブジェクトが有効な画像であることを検証します。
FileField で使える専用の属性に加えて、ImageField には height と width 属性があります。
これらの属性の照会を容易にするために、ImageField には 2 つの追加的な省略可能な引数があります:
- ImageField.height_fieldLink to this definition
モデルインスタンスが保存される度に画像の高さで自動入力される、モデルフィールドの名前です。
- ImageField.width_fieldLink to this definition
モデルインスタンスが保存される度に画像の幅で自動入力される、モデルフィールドの名前です。
Pillow ライブラリを必要とします。
ImageField のインスタンスは、デフォルトが最大 100 文字の varchar カラムとして、データベース上に生成されます。他のフィールドと同様に、max_length 引数を使って最大文字数を変更することができます。
このフィールドのデフォルトのフォームウィジェットは ClearableFileInput です。
IntegerFieldLink to this heading
- class IntegerField(**options)Link to this definition
An integer. Values from -2147483648 to 2147483647 are safe in all
databases supported by Django.
It uses MinValueValidator and
MaxValueValidator to validate the input based
on the values that the default database supports.
このフィールドのデフォルトのフォームウィジェットは、localize が False のとき NumberInput で、そうでなければ TextInput となります。
GenericIPAddressFieldLink to this heading
- class GenericIPAddressField(protocol='both', unpack_ipv4=False, **options)Link to this definition
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.protocolLink to this definition
有効なインプットを、指定したプロトコルに制限します。 使用可能な値は
'both'(デフォルト)、'IPv4'、'IPv6'のどれかです。マッチングは大文字と小文字を区別しません。
- GenericIPAddressField.unpack_ipv4Link to this definition
IPv4 にマッピングされた
::ffff:192.0.2.1のようなアドレスをアンパックします。このオプションを有効にすると、このアドレスは192.0.2.1とアンパックされます。デフォルトは無効です。protocolが'both'に設定されている場合にだけ使用できます。
ブランク値を要する場合、ブランク値は null として保持されるため、null 値を許容する必要があります。
NullBooleanFieldLink to this heading
- class NullBooleanField(**options)Link to this definition
Like BooleanField with null=True. Use that instead of this field
as it's likely to be deprecated in a future version of Django.
PositiveIntegerFieldLink to this heading
- class PositiveIntegerField(**options)Link to this definition
IntegerField とほぼ同じですが、正の値かゼロ (0) でなければなりません。Django によってサポートされる全てのデータベースで、0 から 2147483647 までの値は安全です。後方互換性の理由から、値 0 が有効となっています。
PositiveSmallIntegerFieldLink to this heading
- class PositiveSmallIntegerField(**options)Link to this definition
PositiveIntegerField とほぼ同じですが、特定の (データベースに依存した) ポイントより下の値のみを許容します。Django でサポートされている全てのデータベースで、0 から 32767 までの値は安全です。
SlugFieldLink to this heading
- class SlugField(max_length=50, **options)Link to this definition
Slug is a newspaper term. A slug is a short label for something, containing only letters, numbers, underscores or hyphens. They're generally used in URLs.
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.
It uses validate_slug or
validate_unicode_slug for validation.
- SlugField.allow_unicodeLink to this definition
If
True, the field accepts Unicode letters in addition to ASCII letters. Defaults toFalse.
SmallAutoFieldLink to this heading
- class SmallAutoField(**options)Link to this definition
Like an AutoField, but only allows values under a certain
(database-dependent) limit. Values from 1 to 32767 are safe in all
databases supported by Django.
SmallIntegerFieldLink to this heading
- class SmallIntegerField(**options)Link to this definition
IntegerField とほぼ同じですが、特定の (データベースに依存した) ポイントより下の値のみを許容します。Django でサポートされている全てのデータベースで、-32768 から 32767 までの値は安全です。
TextFieldLink to this heading
- class TextField(**options)Link to this definition
多量のテキストのフィールドです。このフィールドのデフォルトのフォームウィジェットは Textarea です。
max_length 属性を指定した場合、自動生成されたフォームフィールドの Textarea ウィジェット内で反映されます。ただし、モデルやデータベースのレベルでは施行されません。そのためには CharField を使用してください。
TimeFieldLink to this heading
- class TimeField(auto_now=False, auto_now_add=False, **options)Link to this definition
Python で datetime.time インスタンスによって表される時刻です。DateField と同じ自動入力されるオプションを受け入れます。
The default form widget for this field is a TimeInput.
The admin adds some JavaScript shortcuts.
URLFieldLink to this heading
- class URLField(max_length=200, **options)Link to this definition
A CharField for a URL, validated by
URLValidator.
The default form widget for this field is a URLInput.
全ての CharField サブクラスと同じく、URLField は省略可能な max_length 引数を取ります。max_length を指定しない場合、デフォルトの 200 が使われます。
UUIDFieldLink to this heading
- class UUIDField(**options)Link to this definition
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 に渡されます。
Field API referenceLink to this heading
- class FieldLink to this definition
Fieldis an abstract class that represents a database table column. Django uses fields to create the database table (db_type()), to map Python types to database (get_prep_value()) and vice-versa (from_db_value()).A field is thus a fundamental piece in different Django APIs, notably,
modelsandquerysets.In models, a field is instantiated as a class attribute and represents a particular table column, see モデル. It has attributes such as
nullandunique, and methods that Django uses to map the field value to database-specific values.A
Fieldis a subclass ofRegisterLookupMixinand thus bothTransformandLookupcan be registered on it to be used inQuerySets (e.g.field_name__exact="foo"). All built-in lookups are registered by default.All of Django's built-in fields, such as
CharField, are particular implementations ofField. If you need a custom field, you can either subclass any of the built-in fields or write aFieldfrom scratch. In either case, see カスタム model fieldsの実装.- descriptionLink to this definition
A verbose description of the field, e.g. for the
django.contrib.admindocsapplication.The description can be of the form:
description = _("String (up to %(max_length)s)")where the arguments are interpolated from the field's
__dict__.
- descriptor_classLink to this definition
-
A class implementing the descriptor protocol that is instantiated and assigned to the model instance attribute. The constructor must accept a single argument, the
Fieldinstance. Overriding this class attribute allows for customizing the get and set behavior.
To map a
Fieldto a database-specific type, Django exposes several methods:- get_internal_type()Link to this definition
Returns a string naming this field for backend specific purposes. By default, it returns the class name.
See Emulating built-in field types for usage in custom fields.
- db_type(connection)Link to this definition
Returns the database column data type for the
Field, taking into account theconnection.See カスタムデータベースタイプ for usage in custom fields.
- rel_db_type(connection)Link to this definition
Returns the database column data type for fields such as
ForeignKeyandOneToOneFieldthat point to theField, taking into account theconnection.See カスタムデータベースタイプ for usage in custom fields.
There are three main situations where Django needs to interact with the database backend and fields:
when it queries the database (Python value -> database backend value)
when it loads data from the database (database backend value -> Python value)
when it saves to the database (Python value -> database backend value)
When querying,
get_db_prep_value()andget_prep_value()are used:- get_prep_value(value)Link to this definition
valueis the current value of the model's attribute, and the method should return data in a format that has been prepared for use as a parameter in a query.See Converting Python objects to query values for usage.
- get_db_prep_value(value, connection, prepared=False)Link to this definition
Converts
valueto a backend-specific value. By default it returnsvalueifprepared=Trueandget_prep_value()if isFalse.See Converting query values to database values for usage.
When loading data,
from_db_value()is used:- from_db_value(value, expression, connection)Link to this definition
Converts a value as returned by the database to a Python object. It is the reverse of
get_prep_value().This method is not used for most built-in fields as the database backend already returns the correct Python type, or the backend itself does the conversion.
expressionis the same asself.See Converting values to Python objects for usage.
When saving,
pre_save()andget_db_prep_save()are used:- get_db_prep_save(value, connection)Link to this definition
Same as the
get_db_prep_value(), but called when the field value must be saved to the database. By default returnsget_db_prep_value().
- pre_save(model_instance, add)Link to this definition
Method called prior to
get_db_prep_save()to prepare the value before being saved (e.g. forDateField.auto_now).model_instanceis the instance this field belongs to andaddis whether the instance is being saved to the database for the first time.It should return the value of the appropriate attribute from
model_instancefor this field. The attribute name is inself.attname(this is set up byField).See Preprocessing values before saving for usage.
Fields often receive their values as a different type, either from serialization or from forms.
- to_python(value)Link to this definition
Converts the value into the correct Python object. It acts as the reverse of
value_to_string(), and is also called inclean().See Converting values to Python objects for usage.
Besides saving to the database, the field also needs to know how to serialize its value:
- value_from_object(obj)Link to this definition
Returns the field's value for the given model instance.
This method is often used by
value_to_string().
- value_to_string(obj)Link to this definition
Converts
objto a string. Used to serialize the value of the field.See Converting field data for serialization for usage.
When using
model forms, theFieldneeds to know which form field it should be represented by:- formfield(form_class=None, choices_form_class=None, **kwargs)Link to this definition
Returns the default
django.forms.Fieldof this field forModelForm.By default, if both
form_classandchoices_form_classareNone, it usesCharField. If the field haschoicesandchoices_form_classisn't specified, it usesTypedChoiceField.See Specifying the form field for a model field for usage.
- deconstruct()Link to this definition
Returns a 4-tuple with enough information to recreate the field:
The name of the field on the model.
The import path of the field (e.g.
"django.db.models.IntegerField"). This should be the most portable version, so less specific may be better.A list of positional arguments.
A dict of keyword arguments.
This method must be added to fields prior to 1.7 to migrate its data using マイグレーション.
Field attribute referenceLink to this heading
Every Field instance contains several attributes that allow
introspecting its behavior. Use these attributes instead of isinstance
checks when you need to write code that depends on a field's functionality.
These attributes can be used together with the Model._meta API to narrow down a search for specific field types.
Custom model fields should implement these flags.
Attributes for fieldsLink to this heading
- Field.auto_createdLink to this definition
Boolean flag that indicates if the field was automatically created, such as the
OneToOneFieldused by model inheritance.
- Field.concreteLink to this definition
Boolean flag that indicates if the field has a database column associated with it.
Boolean flag that indicates if a field is used to back another non-hidden field's functionality (e.g. the
content_typeandobject_idfields that make up aGenericForeignKey). Thehiddenflag is used to distinguish what constitutes the public subset of fields on the model from all the fields on the model.
- Field.is_relationLink to this definition
Boolean flag that indicates if a field contains references to one or more other models for its functionality (e.g.
ForeignKey,ManyToManyField,OneToOneField, etc.).
- Field.modelLink to this definition
Returns the model on which the field is defined. If a field is defined on a superclass of a model,
modelwill refer to the superclass, not the class of the instance.
Attributes for fields with relationsLink to this heading
These attributes are used to query for the cardinality and other details of a
relation. These attribute are present on all fields; however, they will only
have boolean values (rather than None) if the field is a relation type
(Field.is_relation=True).
- Field.many_to_manyLink to this definition
Boolean flag that is
Trueif the field has a many-to-many relation;Falseotherwise. The only field included with Django where this isTrueisManyToManyField.
- Field.many_to_oneLink to this definition
Boolean flag that is
Trueif the field has a many-to-one relation, such as aForeignKey;Falseotherwise.
- Field.one_to_manyLink to this definition
Boolean flag that is
Trueif the field has a one-to-many relation, such as aGenericRelationor the reverse of aForeignKey;Falseotherwise.
- Field.one_to_oneLink to this definition
Boolean flag that is
Trueif the field has a one-to-one relation, such as aOneToOneField;Falseotherwise.
Points to the model the field relates to. For example,
AuthorinForeignKey(Author, on_delete=models.CASCADE). Therelated_modelfor aGenericForeignKeyis alwaysNone.