---
title: "モデルフィールドリファレンス"
version: 3.1
locale: ja
source: https://docs.djangoproject.com/ja/3.1/ref/models/fields/
canonical: https://djangodocs.dev/ja/3.1/ref/models/fields/
---
# モデルフィールドリファレンス

このドキュメントには、Django が提供する [field options](#field-options) と [field types](#field-types) を含む、[`Field`](#django.db.models.Field) の全ての API リファレンスが記載されています。

> **See also**
>
> 備え付けのフィールドでは目的を達することができない場合、[django-localflavor](https://github.com/django/django-localflavor) ([ドキュメント](https://django-localflavor.readthedocs.io/)) を試すことができます。ここには特定の国や文化に有用なコード部品が、各種取り揃えられています。
>
> さらに、簡単に [あなた自身の独自のモデルフィールドを作ることもできます](/ja/3.1/howto/custom-model-fields/)。

> **Note**
>
> 技術的には、これらのモデルは [`django.db.models.fields`](#module-django.db.models.fields) 内で定義されていまが、利便性のため [`django.db.models`](/ja/3.1/topics/db/models/#module-django.db.models) にインポートされています; 標準的な慣習では、`from django.db import models` を使って、フィールドを `models.<Foo>Field` として参照します。

## フィールドオプション

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

### `null`

#### `Field.null`

```True``の場合、Django はデータベース内に ``NULL``` として空の値を保持します。デフォルトは `False` です。

Avoid using [`null`](#django.db.models.Field.null) on string-based fields such as
[`CharField`](#django.db.models.CharField) and [`TextField`](#django.db.models.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`](#django.db.models.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`](#django.db.models.Field.null) パラメータはデータベーストレー時のみに影響するためです ([`blank`](#django.db.models.Field.blank) を参照してください)。

> **Note**
>
> Oracleのデータベースバックエンドを使っているときには、この属性にかかわらず、値 `NULL` が空の文字列を意味するために保持されます。

### `blank`

#### `Field.blank`

`True` の場合、フィールドはブランクになることが許容されます。デフォルトは `False` です。

[`null`](#django.db.models.Field.null) とは異なる点に注意してください。[`null`](#django.db.models.Field.null) が純粋にデータベースに関連する一方で、[`blank`](#django.db.models.Field.blank) はバリデーションに関連します。フィールドが `blank=True` を持つ場合、フォームバリデーションは空の値のエントリーを許容します。`blank=False` を持つ場合、フィールドは必須となります。

### `choices`

#### `Field.choices`

A [sequence](https://docs.python.org/3/glossary.html#term-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](/ja/3.1/ref/models/instances/#validating-objects) 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.db.models.Field.choices) がセットされているモデルフィールドごとに、Django はフィールドの現在の値に対して人間が読める名前を取得するメソッドを追加します。データベース API ドキュメントの [`get_FOO_display()`](/ja/3.1/ref/models/instances/#django.db.models.Model.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`](#django.db.models.Field.choices) to be dynamic, you're probably better off using
a proper database table with a [`ForeignKey`](#django.db.models.ForeignKey). [`choices`](#django.db.models.Field.choices) is
meant for static data that doesn't change much, if ever.

> **Note**
>
> `choices` の順番を変更すると、変更のたびに新しいマイグレーションが生成されます。

[`blank=False`](#django.db.models.Field.blank) が [`default`](#django.db.models.Field.default) とともにフィールド上にセットされない限り、`"---------"` を含むラベルがセレクトボックスに表示されます。この動作をオーバーライドするためには、`None` を含む `choices` にタプルを追加してください; 例えば `(None, '表示専用の文字列')`. もしくは、`None` の代わりに空の文字列を使うこともできます。これは特に [`CharField`](#django.db.models.CharField) などに適しています。

#### Enumeration types

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`](https://docs.python.org/3/library/enum.html#module-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`. The
  `label` can 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](#field-choices-enum-subclassing) using a more complex
  data type. If a tuple is not provided, or the last item is not a (lazy)
  string, the `label` is [automatically generated](#field-choices-enum-auto-label) from the member name.
- A `.label` property 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 `.choices`
  as a suitable value to pass to [`choices`](#django.db.models.Field.choices) in a field definition.
- The use of [`enum.unique()`](https://docs.python.org/3/library/enum.html#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](https://docs.python.org/3/library/enum.html#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`](https://docs.python.org/3/library/datetime.html#datetime.date) for use with [`DateField`](#django.db.models.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](#field-choices-named-groups).
- Because an enumeration with a concrete data type requires all values to match
  the type, overriding the [blank label](#field-choices-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)')
  ```

> **New in Django 3.0**
>
> The `TextChoices`, `IntegerChoices`, and `Choices` classes were added.

### `db_column`

#### `Field.db_column`

このフィールドを使用するためのデータベースのカラムの名前です。もし与えられなければ、Django はフィールド名を使用します。

データベースのカラム名が SQL の予約語だったり、Python の変数名として使用できない文字 (特に多いのがハイフン) が含まれていたとしても大丈夫です。Django はカラムとテーブルの名前を自動的にクオートして処理してくれます。

### `db_index`

#### `Field.db_index`

`True` の場合、データベースインデックスがこのフィールドのために生成されます。

### `db_tablespace`

#### `Field.db_tablespace`

The name of the [database tablespace](/ja/3.1/topics/db/tablespaces/) to use for
this field's index, if this field is indexed. The default is the project's
[`DEFAULT_INDEX_TABLESPACE`](/ja/3.1/ref/settings/#std-setting-DEFAULT_INDEX_TABLESPACE) setting, if set, or the
[`db_tablespace`](/ja/3.1/ref/models/options/#django.db.models.Options.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`](#django.db.models.JSONField), use a function:

```
def contact_default():
    return {"email": "to1@example.com"}

contact_info = JSONField("ContactInfo", default=contact_default)
```

`lambda`s can't be used for field options like `default` because they
can't be [serialized by migrations](/ja/3.1/topics/migrations/#migration-serializing). See that
documentation for other caveats.

For fields like [`ForeignKey`](#django.db.models.ForeignKey) that map to model instances, defaults
should be the value of the field they reference (`pk` unless
[`to_field`](#django.db.models.ForeignKey.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`](/ja/3.1/topics/forms/modelforms/#django.forms.ModelForm). They are also skipped during [model
validation](/ja/3.1/ref/models/instances/#validating-objects). 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](#field-types) section below.

These error messages often don't propagate to forms. See
[モデルの error\_messages のレンダリングを考える](/ja/3.1/topics/forms/modelforms/#considerations-regarding-model-errormessages).

### `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`](#django.db.models.Field.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()`](/ja/3.1/ref/utils/#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`](#django.db.models.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
[自動インクリメントのプライマリーキーフィールド](/ja/3.1/topics/db/models/#automatic-primary-key-fields).

`primary_key=True` implies [`null=False`](#django.db.models.Field.null) and
[`unique=True`](#django.db.models.Field.unique). 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`](#django.db.models.Field.unique)
field, a [`django.db.IntegrityError`](/ja/3.1/ref/exceptions/#django.db.IntegrityError) will be raised by the model's
[`save()`](/ja/3.1/ref/models/instances/#django.db.models.Model.save) method.

This option is valid on all field types except [`ManyToManyField`](#django.db.models.ManyToManyField) and
[`OneToOneField`](#django.db.models.OneToOneField).

Note that when `unique` is `True`, you don't need to specify
[`db_index`](#django.db.models.Field.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`](#django.db.models.DateField) or [`DateTimeField`](#django.db.models.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`](#django.db.models.DateTimeField), only the date
portion of the field will be considered. Besides, when [`USE_TZ`](/ja/3.1/ref/settings/#std-setting-USE_TZ) is
`True`, the check will be performed in the [current time zone](/ja/3.1/topics/i18n/timezones/#default-current-time-zone) at the time the object gets saved.

This is enforced by [`Model.validate_unique()`](/ja/3.1/ref/models/instances/#django.db.models.Model.validate_unique) during model validation
but not at the database level. If any [`unique_for_date`](#django.db.models.Field.unique_for_date) constraint
involves fields that are not part of a [`ModelForm`](/ja/3.1/topics/forms/modelforms/#django.forms.ModelForm) (for
example, if one of the fields is listed in `exclude` or has
[`editable=False`](#django.db.models.Field.editable)), [`Model.validate_unique()`](/ja/3.1/ref/models/instances/#django.db.models.Model.validate_unique) will
skip validation for that particular constraint.

### `unique_for_month`

#### `Field.unique_for_month`

Like [`unique_for_date`](#django.db.models.Field.unique_for_date), but requires the field to be unique with
respect to the month.

### `unique_for_year`

#### `Field.unique_for_year`

Like [`unique_for_date`](#django.db.models.Field.unique_for_date) and [`unique_for_month`](#django.db.models.Field.unique_for_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](/ja/3.1/topics/db/models/#verbose-field-names).

### `validators`

#### `Field.validators`

A list of validators to run for this field. See the [validators
documentation](/ja/3.1/ref/validators/) for more information.

#### Registering and fetching lookups

`Field` implements the [lookup registration API](/ja/3.1/ref/models/lookups/#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.

## フィールドの型

### `AutoField`

#### `class AutoField(**options)`

利用可能な ID に応じて、自動的にインクリメントする [`IntegerField`](#django.db.models.IntegerField) です。通常は直接使う必要はありません; 指定しない場合は、主キーのフィールドが自動的にモデルに追加されます。[自動インクリメントのプライマリーキーフィールド](/ja/3.1/topics/db/models/#automatic-primary-key-fields) も参照してください。

### `BigAutoField`

#### `class BigAutoField(**options)`

64 ビットの数値です。`1` から `9223372036854775807` までの数を扱える以外は、[`AutoField`](#django.db.models.AutoField) と同じです。

### `BigIntegerField`

#### `class BigIntegerField(**options)`

A 64-bit integer, much like an [`IntegerField`](#django.db.models.IntegerField) except that it is
guaranteed to fit numbers from `-9223372036854775808` to
`9223372036854775807`. The default form widget for this field is a
[`NumberInput`](/ja/3.1/ref/forms/widgets/#django.forms.NumberInput).

### `BinaryField`

#### `class BinaryField(max_length=None, **options)`

A field to store raw binary data. It can be assigned [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes),
[`bytearray`](https://docs.python.org/3/library/stdtypes.html#bytearray), or [`memoryview`](https://docs.python.org/3/library/stdtypes.html#memoryview).

By default, `BinaryField` sets [`editable`](#django.db.models.Field.editable) to `False`, in which
case it can't be included in a [`ModelForm`](/ja/3.1/topics/forms/modelforms/#django.forms.ModelForm).

`BinaryField` has one extra optional argument:

#### `BinaryField.max_length`

The maximum length (in characters) of the field. The maximum length is
enforced in Django's validation using
[`MaxLengthValidator`](/ja/3.1/ref/validators/#django.core.validators.MaxLengthValidator).

> **BinaryField を誤用する**
>
> ファイルをデータベース内に保持したいと考えるかもしれませんが、これは 99% のケースで不適切な設計だということをよく考えてください。このフィールドは適切な [static files](/ja/3.1/howto/static-files/) の処理の代替では *ありません*.

### `BooleanField`

#### `class BooleanField(**options)`

true/false のフィールドです。

The default form widget for this field is [`CheckboxInput`](/ja/3.1/ref/forms/widgets/#django.forms.CheckboxInput),
or [`NullBooleanSelect`](/ja/3.1/ref/forms/widgets/#django.forms.NullBooleanSelect) if [`null=True`](#django.db.models.Field.null).

[`Field.default`](#django.db.models.Field.default) が定義されていないときの `BooleanField` のデフォルト値は `None` です。

### `CharField`

#### `class CharField(max_length=None, **options)`

小 - 大サイズの文字列のフィールドです。

多量のテキストを扱うときは [`TextField`](#django.db.models.TextField) を使ってください。

このフィールドのデフォルトのフォームウィジェットは [`TextInput`](/ja/3.1/ref/forms/widgets/#django.forms.TextInput) です。

[`CharField`](#django.db.models.CharField) には追加的な必須の引数があります:

#### `CharField.max_length`

The maximum length (in characters) of the field. The max\_length is enforced
at the database level and in Django's validation using
[`MaxLengthValidator`](/ja/3.1/ref/validators/#django.core.validators.MaxLengthValidator).

> **Note**
>
> 複数のデータベースバックエンド間で使われるアプリケーションを作る場合は、いくつかのバックエンドで `max_length` に制限があることに注意しなければなりません。詳しくは [database backend notes](/ja/3.1/ref/databases/) を参照してください。

### `DateField`

#### `class DateField(auto_now=False, auto_now_add=False, **options)`

Python で `datetime.date` インスタンスによって表される日付です。多少の追加的な省略可能な引数を持ちます:

#### `DateField.auto_now`

オブジェクトが保存される度に自動的に現在の日付をセットします。"最後の変更" タイムスタンプに役立ちます。現在の日付が常に使われる点に注意してください; オーバーライドできる単なるデフォルト値ではありません。

[`Model.save()`](/ja/3.1/ref/models/instances/#django.db.models.Model.save) が呼ばれたとき、フィールドは自動的に更新されるだけです。[`QuerySet.update()`](/ja/3.1/ref/models/querysets/#django.db.models.query.QuerySet.update) のような別の方法で他のフィールドに更新を加えるとき、フィールドは更新されません。あのように更新の中でフィールドの独自の値を指定できるとしてもです。

#### `DateField.auto_now_add`

オブジェクトが最初に作成されるとき、自動的にフィールドに現在の日付をセットします。タイムスタンプの作成に役立ちます。現在の日付が *常に* 使われる点に注意してください; オーバーライドできる単なるデフォルト値ではありません。たとえオブジェクトを作成するときに値をセットしたとしても無視されます。このフィールドを修正できるようにしておきたい場合は、`auto_now_add=True` の代わりに以下をセットしてください:

- [`DateField`](#django.db.models.DateField) に対して: `default=date.today` \- [`datetime.date.today()`](https://docs.python.org/3/library/datetime.html#datetime.date.today) より
- [`DateTimeField`](#django.db.models.DateTimeField) に対して: `default=timezone.now` \- [`django.utils.timezone.now()`](/ja/3.1/ref/utils/#django.utils.timezone.now) より

The default form widget for this field is a
[`DateInput`](/ja/3.1/ref/forms/widgets/#django.forms.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\` は相互に排他的です。これらのオプションを組み合わせるとエラーが発生します。

> **Note**
>
> 現在実装されているように、`auto_now` や `auto_now_add` を `True` にセットすると、フィールドは `editable=False` と `blank=True` にセットされます。

> **Note**
>
> The `auto_now` and `auto_now_add` options will always use the date in
> the [default timezone](/ja/3.1/topics/i18n/timezones/#default-current-time-zone) at the moment of
> creation or update. If you need something different, you may want to
> consider 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`](#django.db.models.DateField) と同じくいくつかの追加的な引数を持ちます:

The default form widget for this field is a single
[`DateTimeInput`](/ja/3.1/ref/forms/widgets/#django.forms.DateTimeInput). The admin uses two separate
[`TextInput`](/ja/3.1/ref/forms/widgets/#django.forms.TextInput) widgets with JavaScript shortcuts.

### `DecimalField`

#### `class DecimalField(max_digits=None, decimal_places=None, **options)`

A fixed-precision decimal number, represented in Python by a
[`Decimal`](https://docs.python.org/3/library/decimal.html#decimal.Decimal) instance. It validates the input using
[`DecimalValidator`](/ja/3.1/ref/validators/#django.core.validators.DecimalValidator).

Has two **required** arguments:

#### `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`](/ja/3.1/ref/forms/fields/#django.forms.Field.localize) が `False` のとき [`NumberInput`](/ja/3.1/ref/forms/widgets/#django.forms.NumberInput) で、そうでなければ [`TextInput`](/ja/3.1/ref/forms/widgets/#django.forms.TextInput) となります。

> **Note**
>
> For more information about the differences between the
> [`FloatField`](#django.db.models.FloatField) and [`DecimalField`](#django.db.models.DecimalField) classes, please
> see [FloatField vs. DecimalField](#floatfield-vs-decimalfield). You
> should also be aware of [SQLite limitations](/ja/3.1/ref/databases/#sqlite-decimal-handling)
> of decimal fields.

### `DurationField`

#### `class DurationField(**options)`

時刻の期間を保持するフィールドで、 Python の [`timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta) によってモデル化されます。PostgreSQL で使われるときに用いられるデータ型は `interval` で、Oracle でのデータ型は ```INTERVAL DAY(9) TO SECOND(6)``です。 それ以外では、マイクロ秒の ``bigint``` が使われます。

> **Note**
>
> `DurationField` での演算はほとんどの場合で機能します。ただし、PostgreSQL 以外のデータベースでは、`DurationField` の値と `DateTimeField` インスタンス上の演算を比較することは期待通りに機能しません。

### `EmailField`

#### `class EmailField(max_length=254, **options)`

A [`CharField`](#django.db.models.CharField) that checks that the value is a valid email address using
[`EmailValidator`](/ja/3.1/ref/validators/#django.core.validators.EmailValidator).

### `FileField`

#### `class FileField(upload_to=None, max_length=100, **options)`

ファイルアップロードのフィールドです。

> **Note**
>
> The `primary_key` argument isn't supported and will raise an error if
> used.

2 つの省略可能な引数があります:

#### `FileField.upload_to`

この属性は、アップロードディレクトリとファイル名を設定する方法を提供し、2 つの方法でセットできます。どちらの場合も、値は [`Storage.save()`](/ja/3.1/ref/files/storage/#django.core.files.storage.Storage.save) メソッドに渡されます。

If you specify a string value or a [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path), it may contain
[`strftime()`](https://docs.python.org/3/library/time.html#time.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`](/ja/3.1/ref/files/storage/#django.core.files.storage.FileSystemStorage), the string value
will be appended to your [`MEDIA_ROOT`](/ja/3.1/ref/settings/#std-setting-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<br>`FileField` is defined. More specifically,<br>this is the particular instance where the<br>current file is being attached.<br><br>In most cases, this object will not have been<br>saved to the database yet, so if it uses the<br>default `AutoField`, *it might not yet have a<br>value for its primary key field*. |
| `filename` | The filename that was originally given to the<br>file. This may or may not be taken into account<br>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)
```

> **Changed in Django 3.0**
>
> Support for [`pathlib.Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path) was added.

#### `FileField.storage`

A storage object, or a callable which returns a storage object. This
handles the storage and retrieval of your files. See [ファイルの管理](/ja/3.1/topics/files/)
for details on how to provide this object.

> **Changed in Django 3.1**
>
> The ability to provide a callable was added.

このフィールドのデフォルトのフォームウィジェットは [`ClearableFileInput`](/ja/3.1/ref/forms/widgets/#django.forms.ClearableFileInput) です。

モデル内で a [`FileField`](#django.db.models.FileField) や [`ImageField`](#django.db.models.ImageField) (後述) 使うにはいくつかのステップを取ります:

1. 設定ファイル内で [`MEDIA_ROOT`](/ja/3.1/ref/settings/#std-setting-MEDIA_ROOT) を指定します。この値は、Django がアップロードされたファイルを置く場所にします (パフォーマン ス上の理由から、ファイルをデータベースに置くことはありません)。 [`MEDIA_URL`](/ja/3.1/ref/settings/#std-setting-MEDIA_URL) をそのディレクトリの公開 URL にします。ディレク トリは Web サーバのユーザアカウントに対して書き込み可能にしておかねばなりません。
2. Add the [`FileField`](#django.db.models.FileField) or [`ImageField`](#django.db.models.ImageField) to your model, defining
   the [`upload_to`](#django.db.models.FileField.upload_to) option to specify a subdirectory of
   [`MEDIA_ROOT`](/ja/3.1/ref/settings/#std-setting-MEDIA_ROOT) to use for uploaded files.
3. All that will be stored in your database is a path to the file
   (relative to [`MEDIA_ROOT`](/ja/3.1/ref/settings/#std-setting-MEDIA_ROOT)). You'll most likely want to use the
   convenience [`url`](#django.db.models.fields.files.FieldFile.url) attribute
   provided by Django. For example, if your [`ImageField`](#django.db.models.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`](/ja/3.1/ref/settings/#std-setting-MEDIA_ROOT) is set to `'/home/media'`, and
[`upload_to`](#django.db.models.FileField.upload_to) is set to `'photos/%Y/%m/%d'`. The `'%Y/%m/%d'`
part of [`upload_to`](#django.db.models.FileField.upload_to) is [`strftime()`](https://docs.python.org/3/library/time.html#time.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`](/ja/3.1/ref/files/file/#django.core.files.File.name) and
[`size`](/ja/3.1/ref/files/file/#django.core.files.File.size) attributes respectively; for more
information on the available attributes and methods, see the
[`File`](/ja/3.1/ref/files/file/#django.core.files.File) class reference and the [ファイルの管理](/ja/3.1/topics/files/)
topic guide.

> **Note**
>
> 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`](#django.db.models.fields.files.FieldFile.url) attribute. Internally,
this calls the [`url()`](/ja/3.1/ref/files/storage/#django.core.files.storage.Storage.url) method of the
underlying [`Storage`](/ja/3.1/ref/files/storage/#django.core.files.storage.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`](#django.db.models.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`](#django.db.models.CharField.max_length) argument.

#### `FileField` と `FieldFile`

#### `class FieldFile`

モデル上の [`FileField`](#django.db.models.FileField) にアクセスするとき、元となるファイルにアアクセスするためのプロキシとして、[`FieldFile`](#django.db.models.fields.files.FieldFile) のインスタンスが与えられます。

[`FieldFile`](#django.db.models.fields.files.FieldFile)  の API は [`File`](/ja/3.1/ref/files/file/#django.core.files.File) の API を反映していますが、主な違いが 1 つあります: *クラスによってラップされたオブジェクトは必ずしも Python のビルトインのファイルオブジェクトのラッパーであるとは限りません。* 代わりに、[`Storage.open()`](/ja/3.1/ref/files/storage/#django.core.files.storage.Storage.open) メソッドの結果を包むラッパーで、これは  [`File`](/ja/3.1/ref/files/file/#django.core.files.File) オブジェクトもしくは [`File`](/ja/3.1/ref/files/file/#django.core.files.File) API の独自ストレージの実装となります。

In addition to the API inherited from [`File`](/ja/3.1/ref/files/file/#django.core.files.File) such as
`read()` and `write()`, [`FieldFile`](#django.db.models.fields.files.FieldFile) includes several methods that
can be used to interact with the underlying file:

> **Warning**
>
> このクラスの 2 つのメソッド、[`save()`](#django.db.models.fields.files.FieldFile.save) と [`delete()`](#django.db.models.fields.files.FieldFile.delete) は、デフォルトで、関連する FieldFile のモデルオブジェクトをデータベースに保存します。

#### `FieldFile.name`

関連する [`FileField`](#django.db.models.FileField) の [`Storage`](/ja/3.1/ref/files/storage/#django.core.files.storage.Storage) のルートからの相対パスを含むファイル名です。

#### `FieldFile.path`

A read-only property to access the file's local filesystem path by calling the
[`path()`](/ja/3.1/ref/files/storage/#django.core.files.storage.Storage.path) method of the underlying
[`Storage`](/ja/3.1/ref/files/storage/#django.core.files.storage.Storage) class.

#### `FieldFile.size`

元となる [`Storage.size()`](/ja/3.1/ref/files/storage/#django.core.files.storage.Storage.size) メソッドの結果です。

#### `FieldFile.url`

元となる [`Storage`](/ja/3.1/ref/files/storage/#django.core.files.storage.Storage) クラス の [`url()`](/ja/3.1/ref/files/storage/#django.core.files.storage.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`](/ja/3.1/ref/files/file/#django.core.files.File) のインスタンスでなければならないことに注意してください。 以下のように、既存の Python ファイルオブジェクトから [`File`](/ja/3.1/ref/files/file/#django.core.files.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")
```

より詳しくは [ファイルの管理](/ja/3.1/topics/files/) をご覧ください。

#### `FieldFile.delete(save=True)`

このインスタンスに関連付けられているファイルを削除し、フィールドのすべての属性をクリアします。 注: このメソッドは、`delete()` が呼び出されたときにファイルが開いた場合、ファイルを閉じます。

省略可能な `save` 引数は、このフィールドに関連付けられたファイルが削除された後にモデルインスタンスを保存するかどうかをコントロールします。 デフォルトは `True` です。

モデルを削除するとき、関連ファイルは削除されない点に注意してください。 孤立したファイルをクリーンアップする必要がある場合、自分で処理する必要があります (例えば、手動で実行したり、例えば cron などを通して定期的に実行される、独自の管理コマンドです)。

### `FilePathField`

#### `class FilePathField(path='', match=None, recursive=False, allow_files=True, allow_folders=False, max_length=100, **options)`

A [`CharField`](#django.db.models.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.path`

必須です。[`FilePathField`](#django.db.models.FilePathField) が選択肢から取得するディレクトリへの、ファイルシステムの絶対パスです。例: `"/home/images"`。

`path` may 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)
```

> **Changed in Django 3.0**
>
> `path` can now be a callable.

#### `FilePathField.match`

省略可能です。正規表現で、文字列として、[`FilePathField`](#django.db.models.FilePathField) がファイル名をフィルタリングするために使用します。 正規表現は、フルパスではなくベースファイル名に適用される点に注意してください。 例: `"foo.*\.txt$"`。これは `foo23.txt` とは合致しますが、`bar.txt` や `foo23.png` とは合致しません。

#### `FilePathField.recursive`

省略可能です。`True` か `False` のどちらかを取り、デフォルトは `False` です。[`path`](#django.db.models.FilePathField.path) の全てのサブディレクトリを含むかどうかを指定します。

#### `FilePathField.allow_files`

省略可能です。`True` か `False` を取り、デフォルトは `True` です。指定された場所にあるファイルを含むかどうかを指定します。 これか [`allow_folders`](#django.db.models.FilePathField.allow_folders) のどちらかを `True` にする必要があります。

#### `FilePathField.allow_folders`

省略可能です。`True` か `False` を取り、デフォルトは `False` です。指定した場所にあるフォルダーを含むかどうかを指定します。これか [`allow_files`](#django.db.models.FilePathField.allow_files) のどちらかを `True` にする必要があります。

1つの可能性は、フルパスではなく、ベースファイル名に [`match`](#django.db.models.FilePathField.match) が適用されることです。 したがって、この例:

```
FilePathField(path="/home/images", match="foo.*", recursive=True)
```

...は、`/home/images/foo/bar.png` ではなく `/home/images/foo.png` とマッチします。これは、[`match`](#django.db.models.FilePathField.match) がベースのファイル名に適用されるからです (`foo.png` と `bar.png`)。

[`FilePathField`](#django.db.models.FilePathField) のインスタンスは、デフォルトが最大 100 文字の `varchar` カラムとして、データベース上に生成されます。他のフィールドと同様に、[`max_length`](#django.db.models.CharField.max_length) 引数を使って最大文字数を変更することができます。

### `FloatField`

#### `class FloatField(**options)`

`float` インスタンスによって表される Python の浮動小数点数です。

このフィールドのデフォルトのフォームウィジェットは、[`localize`](/ja/3.1/ref/forms/fields/#django.forms.Field.localize) が `False` のとき [`NumberInput`](/ja/3.1/ref/forms/widgets/#django.forms.NumberInput) で、そうでなければ [`TextInput`](/ja/3.1/ref/forms/widgets/#django.forms.TextInput) となります。

> **FloatField と DecimalField の比較**
>
> [`FloatField`](#django.db.models.FloatField) クラスは、[`DecimalField`](#django.db.models.DecimalField) クラスと混同されることがあります。両方とも実数を表しますが、異なる方法で表現しています。`FloatField` は内部的には Python の `float` 型を使い、`DecimalField` は Python の `Decimal` 型を使います。この 2 つの違いについては、 Python のドキュメント [`decimal`](https://docs.python.org/3/library/decimal.html#module-decimal) module を参照してください。

### `ImageField`

#### `class ImageField(upload_to=None, height_field=None, width_field=None, max_length=100, **options)`

[`FileField`](#django.db.models.FileField) から全ての属性とメソッドを継承して、さらにアップロードされたオブジェクトが有効な画像であることを検証します。

[`FileField`](#django.db.models.FileField) で使える専用の属性に加えて、[`ImageField`](#django.db.models.ImageField) には `height` と `width` 属性があります。

これらの属性の照会を容易にするために、[`ImageField`](#django.db.models.ImageField) には 2 つの追加的な省略可能な引数があります:

#### `ImageField.height_field`

モデルインスタンスが保存される度に画像の高さで自動入力される、モデルフィールドの名前です。

#### `ImageField.width_field`

モデルインスタンスが保存される度に画像の幅で自動入力される、モデルフィールドの名前です。

[Pillow](https://pillow.readthedocs.io/en/latest/) ライブラリを必要とします。

[`ImageField`](#django.db.models.ImageField) のインスタンスは、デフォルトが最大 100 文字の `varchar` カラムとして、データベース上に生成されます。他のフィールドと同様に、[`max_length`](#django.db.models.CharField.max_length) 引数を使って最大文字数を変更することができます。

このフィールドのデフォルトのフォームウィジェットは [`ClearableFileInput`](/ja/3.1/ref/forms/widgets/#django.forms.ClearableFileInput) です。

### `IntegerField`

#### `class IntegerField(**options)`

An integer. Values from `-2147483648` to `2147483647` are safe in all
databases supported by Django.

It uses [`MinValueValidator`](/ja/3.1/ref/validators/#django.core.validators.MinValueValidator) and
[`MaxValueValidator`](/ja/3.1/ref/validators/#django.core.validators.MaxValueValidator) to validate the input based
on the values that the default database supports.

このフィールドのデフォルトのフォームウィジェットは、[`localize`](/ja/3.1/ref/forms/fields/#django.forms.Field.localize) が `False` のとき [`NumberInput`](/ja/3.1/ref/forms/widgets/#django.forms.NumberInput) で、そうでなければ [`TextInput`](/ja/3.1/ref/forms/widgets/#django.forms.TextInput) となります。

### `GenericIPAddressField`

#### `class GenericIPAddressField(protocol='both', unpack_ipv4=False, **options)`

IPv4 か IPv6 のアドレスで、文字列フォーマットです (例: `192.0.2.30` ないし `2a02:42fe::4`)。このフィールドのデフォルトのフォームウィジェットは [`TextInput`](/ja/3.1/ref/forms/widgets/#django.forms.TextInput) です。

IPv6 アドレスは、 [**RFC 4291 Section 2.2**](https://datatracker.ietf.org/doc/html/rfc4291.html#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 値を許容する必要があります。

### `JSONField`

#### `class JSONField(encoder=None, decoder=None, **options)`

> **New in Django 3.1**

A field for storing JSON encoded data. In Python the data is represented in its
Python native format: dictionaries, lists, strings, numbers, booleans and
`None`.

`JSONField` is supported on MariaDB 10.2.7+, MySQL 5.7.8+, Oracle,
PostgreSQL, and SQLite 3.9.0+ (with the [JSON1 extension enabled](/ja/3.1/ref/databases/#sqlite-json1)).

#### `JSONField.encoder`

An optional [`json.JSONEncoder`](https://docs.python.org/3/library/json.html#json.JSONEncoder) subclass to serialize data types
not supported by the standard JSON serializer (e.g. `datetime.datetime`
or [`UUID`](https://docs.python.org/3/library/uuid.html#uuid.UUID)). For example, you can use the
[`DjangoJSONEncoder`](/ja/3.1/topics/serialization/#django.core.serializers.json.DjangoJSONEncoder) class.

Defaults to `json.JSONEncoder`.

#### `JSONField.decoder`

An optional [`json.JSONDecoder`](https://docs.python.org/3/library/json.html#json.JSONDecoder) subclass to deserialize the value
retrieved from the database. The value will be in the format chosen by the
custom encoder (most often a string). Your deserialization may need to
account for the fact that you can't be certain of the input type. For
example, you run the risk of returning a `datetime` that was actually a
string that just happened to be in the same format chosen for
`datetime`s.

Defaults to `json.JSONDecoder`.

If you give the field a [`default`](#django.db.models.Field.default), ensure it's an
immutable object, such as a `str`, or a callable object that returns a fresh
mutable object each time, such as `dict` or a function. Providing a mutable
default object like `default={}` or `default=[]` shares the one object
between all model instances.

To query `JSONField` in the database, see [Querying JSONField](/ja/3.1/topics/db/queries/#querying-jsonfield).

> **Indexing**
>
> [`Index`](/ja/3.1/ref/models/indexes/#django.db.models.Index) and [`Field.db_index`](#django.db.models.Field.db_index) both create a
> B-tree index, which isn't particularly helpful when querying `JSONField`.
> On PostgreSQL only, you can use
> [`GinIndex`](/ja/3.1/ref/contrib/postgres/indexes/#django.contrib.postgres.indexes.GinIndex) that is better suited.

> **PostgreSQL users**
>
> PostgreSQL has two native JSON based data types: `json` and `jsonb`.
> The main difference between them is how they are stored and how they can be
> queried. PostgreSQL's `json` field is stored as the original string
> representation of the JSON and must be decoded on the fly when queried
> based on keys. The `jsonb` field is stored based on the actual structure
> of the JSON which allows indexing. The trade-off is a small additional cost
> on writing to the `jsonb` field. `JSONField` uses `jsonb`.

> **Oracle users**
>
> Oracle Database does not support storing JSON scalar values. Only JSON
> objects and arrays (represented in Python using [`dict`](https://docs.python.org/3/library/stdtypes.html#dict) and
> [`list`](https://docs.python.org/3/library/stdtypes.html#list)) are supported.

### `NullBooleanField`

#### `class NullBooleanField(**options)`

Like [`BooleanField`](#django.db.models.BooleanField) with `null=True`.

> **Deprecated since Django 3.1**
>
> バージョン 3.1 で非推奨: `NullBooleanField` is deprecated in favor of `BooleanField(null=True)`.

### `PositiveBigIntegerField`

#### `class PositiveBigIntegerField(**options)`

> **New in Django 3.1**

Like a [`PositiveIntegerField`](#django.db.models.PositiveIntegerField), but only allows values under a certain
(database-dependent) point. Values from `0` to `9223372036854775807` are
safe in all databases supported by Django.

### `PositiveIntegerField`

#### `class PositiveIntegerField(**options)`

[`IntegerField`](#django.db.models.IntegerField) とほぼ同じですが、正の値かゼロ (`0`) でなければなりません。Django によってサポートされる全てのデータベースで、`0` から `2147483647` までの値は安全です。後方互換性の理由から、値 `0` が有効となっています。

### `PositiveSmallIntegerField`

#### `class PositiveSmallIntegerField(**options)`

[`PositiveIntegerField`](#django.db.models.PositiveIntegerField) とほぼ同じですが、特定の (データベースに依存した) ポイントより下の値のみを許容します。Django でサポートされている全てのデータベースで、`0` から `32767` までの値は安全です。

### `SlugField`

#### `class SlugField(max_length=50, **options)`

[Slug](/ja/3.1/glossary/#term-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`](#django.db.models.CharField.max_length) を指定することもできます (データベースの可搬性についてのノートとそのセクションの [`max_length`](#django.db.models.CharField.max_length) も参照してください)。[`max_length`](#django.db.models.CharField.max_length) が指定されていないとき、Django はデフォルトの文字数 50 を使います。

暗黙的に [`Field.db_index`](#django.db.models.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`](/ja/3.1/ref/contrib/admin/#django.contrib.admin.ModelAdmin.prepopulated_fields).

It uses [`validate_slug`](/ja/3.1/ref/validators/#django.core.validators.validate_slug) or
[`validate_unicode_slug`](/ja/3.1/ref/validators/#django.core.validators.validate_unicode_slug) for validation.

#### `SlugField.allow_unicode`

If `True`, the field accepts Unicode letters in addition to ASCII
letters. Defaults to `False`.

### `SmallAutoField`

#### `class SmallAutoField(**options)`

> **New in Django 3.0**

Like an [`AutoField`](#django.db.models.AutoField), but only allows values under a certain
(database-dependent) limit. Values from `1` to `32767` are safe in all
databases supported by Django.

### `SmallIntegerField`

#### `class SmallIntegerField(**options)`

[`IntegerField`](#django.db.models.IntegerField) とほぼ同じですが、特定の (データベースに依存した) ポイントより下の値のみを許容します。Django でサポートされている全てのデータベースで、`-32768` から `32767` までの値は安全です。

### `TextField`

#### `class TextField(**options)`

多量のテキストのフィールドです。このフィールドのデフォルトのフォームウィジェットは  [`Textarea`](/ja/3.1/ref/forms/widgets/#django.forms.Textarea) です。

`max_length` 属性を指定した場合、自動生成されたフォームフィールドの [`Textarea`](/ja/3.1/ref/forms/widgets/#django.forms.Textarea) ウィジェット内で反映されます。ただし、モデルやデータベースのレベルでは施行されません。そのためには [`CharField`](#django.db.models.CharField) を使用してください。

### `TimeField`

#### `class TimeField(auto_now=False, auto_now_add=False, **options)`

Python で `datetime.time` インスタンスによって表される時刻です。[`DateField`](#django.db.models.DateField) と同じ自動入力されるオプションを受け入れます。

The default form widget for this field is a [`TimeInput`](/ja/3.1/ref/forms/widgets/#django.forms.TimeInput).
The admin adds some JavaScript shortcuts.

### `URLField`

#### `class URLField(max_length=200, **options)`

A [`CharField`](#django.db.models.CharField) for a URL, validated by
[`URLValidator`](/ja/3.1/ref/validators/#django.core.validators.URLValidator).

The default form widget for this field is a [`URLInput`](/ja/3.1/ref/forms/widgets/#django.forms.URLInput).

全ての [`CharField`](#django.db.models.CharField) サブクラスと同じく、[`URLField`](#django.db.models.URLField) は省略可能な [`max_length`](#django.db.models.CharField.max_length) 引数を取ります。[`max_length`](#django.db.models.CharField.max_length) を指定しない場合、デフォルトの 200 が使われます。

### `UUIDField`

#### `class UUIDField(**options)`

UUID (Universally Unique Identifier) を保持するためのフィールドです。Python's [`UUID`](https://docs.python.org/3/library/uuid.html#uuid.UUID) クラスを使います。 PostgreSQL 上で使われるとき、`uuid` データ型の中に保持します。それ以外は `char(32)` の中に保持します。

UUID は attr:~Field.primary\_key に代わる [`AutoField`](#django.db.models.AutoField) への良い選択肢です。 データベースはあなたのための UUID を生成しないため、[`default`](#django.db.models.Field.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` に渡されます。

> **Lookups on PostgreSQL**
>
> Using [`iexact`](/ja/3.1/ref/models/querysets/#std-fieldlookup-iexact), [`contains`](/ja/3.1/ref/models/querysets/#std-fieldlookup-contains), [`icontains`](/ja/3.1/ref/models/querysets/#std-fieldlookup-icontains),
> [`startswith`](/ja/3.1/ref/models/querysets/#std-fieldlookup-startswith), [`istartswith`](/ja/3.1/ref/models/querysets/#std-fieldlookup-istartswith), [`endswith`](/ja/3.1/ref/models/querysets/#std-fieldlookup-endswith), or
> [`iendswith`](/ja/3.1/ref/models/querysets/#std-fieldlookup-iendswith) lookups on PostgreSQL don't work for values without
> hyphens, because PostgreSQL stores them in a hyphenated uuid datatype type.

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

Djangoは、リレーションを表すフィールドのセットも定義しています。

### `ForeignKey`

#### `class ForeignKey(to, on_delete, **options)`

A many-to-one relationship. Requires two positional arguments: the class to
which the model is related and the [`on_delete`](#django.db.models.ForeignKey.on_delete) option.

To create a recursive relationship -- an object that has a many-to-one
relationship with itself -- use `models.ForeignKey('self',
on_delete=models.CASCADE)`.

If you need to create a relationship on a model that has not yet been defined,
you can use the name of the model, rather than the model object itself:

```
from django.db import models

class Car(models.Model):
    manufacturer = models.ForeignKey(
        'Manufacturer',
        on_delete=models.CASCADE,
    )
    # ...

class Manufacturer(models.Model):
    # ...
    pass
```

Relationships defined this way on [abstract models](/ja/3.1/topics/db/models/#abstract-base-classes) are resolved when the model is subclassed as a
concrete model and are not relative to the abstract model's `app_label`:

*products/models.py*

```python
from django.db import models

class AbstractCar(models.Model):
    manufacturer = models.ForeignKey('Manufacturer', on_delete=models.CASCADE)

    class Meta:
        abstract = True
```

*production/models.py*

```python
from django.db import models
from products.models import AbstractCar

class Manufacturer(models.Model):
    pass

class Car(AbstractCar):
    pass

# Car.manufacturer will point to `production.Manufacturer` here.
```

To refer to models defined in another application, you can explicitly specify
a model with the full application label. For example, if the `Manufacturer`
model above is defined in another application called `production`, you'd
need to use:

```
class Car(models.Model):
    manufacturer = models.ForeignKey(
        'production.Manufacturer',
        on_delete=models.CASCADE,
    )
```

This sort of reference, called a lazy relationship, can be useful when
resolving circular import dependencies between two applications.

A database index is automatically created on the `ForeignKey`. You can
disable this by setting [`db_index`](#django.db.models.Field.db_index) to `False`.  You may want to
avoid the overhead of an index if you are creating a foreign key for
consistency rather than joins, or if you will be creating an alternative index
like a partial or multiple column index.

#### Database Representation

Behind the scenes, Django appends `"_id"` to the field name to create its
database column name. In the above example, the database table for the `Car`
model will have a `manufacturer_id` column. (You can change this explicitly by
specifying [`db_column`](#django.db.models.Field.db_column)) However, your code should never have to
deal with the database column name, unless you write custom SQL. You'll always
deal with the field names of your model object.

#### 引数

[`ForeignKey`](#django.db.models.ForeignKey) accepts other arguments that define the details of how the
relation works.

#### `ForeignKey.on_delete`

When an object referenced by a [`ForeignKey`](#django.db.models.ForeignKey) is deleted, Django will
emulate the behavior of the SQL constraint specified by the
[`on_delete`](#django.db.models.ForeignKey.on_delete) argument. For example, if you have a nullable
[`ForeignKey`](#django.db.models.ForeignKey) and you want it to be set null when the referenced
object is deleted:

```
user = models.ForeignKey(
    User,
    models.SET_NULL,
    blank=True,
    null=True,
)
```

`on_delete` doesn't create an SQL constraint in the database. Support for
database-level cascade options [may be implemented later](https://code.djangoproject.com/ticket/21961).

The possible values for [`on_delete`](#django.db.models.ForeignKey.on_delete) are found in
[`django.db.models`](/ja/3.1/topics/db/models/#module-django.db.models):

- #### `CASCADE`

  Cascade deletes. Django emulates the behavior of the SQL constraint ON
  DELETE CASCADE and also deletes the object containing the ForeignKey.

  [`Model.delete()`](/ja/3.1/ref/models/instances/#django.db.models.Model.delete) isn't called on related models, but the
  [`pre_delete`](/ja/3.1/ref/signals/#django.db.models.signals.pre_delete) and
  [`post_delete`](/ja/3.1/ref/signals/#django.db.models.signals.post_delete) signals are sent for all
  deleted objects.
- #### `PROTECT`

  Prevent deletion of the referenced object by raising
  [`ProtectedError`](/ja/3.1/ref/exceptions/#django.db.models.ProtectedError), a subclass of
  [`django.db.IntegrityError`](/ja/3.1/ref/exceptions/#django.db.IntegrityError).
- #### `RESTRICT`

  > **New in Django 3.1**

  Prevent deletion of the referenced object by raising
  [`RestrictedError`](/ja/3.1/ref/exceptions/#django.db.models.RestrictedError) (a subclass of
  [`django.db.IntegrityError`](/ja/3.1/ref/exceptions/#django.db.IntegrityError)). Unlike [`PROTECT`](#django.db.models.PROTECT), deletion of the
  referenced object is allowed if it also references a different object
  that is being deleted in the same operation, but via a [`CASCADE`](#django.db.models.CASCADE)
  relationship.

  以下のような一連のモデルを考えていきましょう:

  ```
  class Artist(models.Model):
      name = models.CharField(max_length=10)

  class Album(models.Model):
      artist = models.ForeignKey(Artist, on_delete=models.CASCADE)

  class Song(models.Model):
      artist = models.ForeignKey(Artist, on_delete=models.CASCADE)
      album = models.ForeignKey(Album, on_delete=models.RESTRICT)
  ```

  `Artist` can be deleted even if that implies deleting an `Album`
  which is referenced by a `Song`, because `Song` also references
  `Artist` itself through a cascading relationship. For example:

  ```
  >>> artist_one = Artist.objects.create(name='artist one')
  >>> artist_two = Artist.objects.create(name='artist two')
  >>> album_one = Album.objects.create(artist=artist_one)
  >>> album_two = Album.objects.create(artist=artist_two)
  >>> song_one = Song.objects.create(artist=artist_one, album=album_one)
  >>> song_two = Song.objects.create(artist=artist_one, album=album_two)
  >>> album_one.delete()
  # Raises RestrictedError.
  >>> artist_two.delete()
  # Raises RestrictedError.
  >>> artist_one.delete()
  (4, {'Song': 2, 'Album': 1, 'Artist': 1})
  ```
- #### `SET_NULL`

  Set the [`ForeignKey`](#django.db.models.ForeignKey) null; this is only possible if
  [`null`](#django.db.models.Field.null) is `True`.
- #### `SET_DEFAULT`

  Set the [`ForeignKey`](#django.db.models.ForeignKey) to its default value; a default for the
  [`ForeignKey`](#django.db.models.ForeignKey) must be set.
- #### `SET()`

  Set the [`ForeignKey`](#django.db.models.ForeignKey) to the value passed to
  [`SET()`](#django.db.models.SET), or if a callable is passed in,
  the result of calling it. In most cases, passing a callable will be
  necessary to avoid executing queries at the time your models.py is
  imported:

  ```
  from django.conf import settings
  from django.contrib.auth import get_user_model
  from django.db import models

  def get_sentinel_user():
      return get_user_model().objects.get_or_create(username='deleted')[0]

  class MyModel(models.Model):
      user = models.ForeignKey(
          settings.AUTH_USER_MODEL,
          on_delete=models.SET(get_sentinel_user),
      )
  ```
- #### `DO_NOTHING`

  Take no action. If your database backend enforces referential
  integrity, this will cause an [`IntegrityError`](/ja/3.1/ref/exceptions/#django.db.IntegrityError) unless
  you manually add an SQL `ON DELETE` constraint to the database field.

#### `ForeignKey.limit_choices_to`

Sets a limit to the available choices for this field when this field is
rendered using a `ModelForm` or the admin (by default, all objects
in the queryset are available to choose). Either a dictionary, a
[`Q`](/ja/3.1/ref/models/querysets/#django.db.models.Q) object, or a callable returning a
dictionary or [`Q`](/ja/3.1/ref/models/querysets/#django.db.models.Q) object can be used.

例:

```
staff_member = models.ForeignKey(
    User,
    on_delete=models.CASCADE,
    limit_choices_to={'is_staff': True},
)
```

causes the corresponding field on the `ModelForm` to list only `Users`
that have `is_staff=True`. This may be helpful in the Django admin.

The callable form can be helpful, for instance, when used in conjunction
with the Python `datetime` module to limit selections by date range. For
example:

```
def limit_pub_date_choices():
    return {'pub_date__lte': datetime.date.utcnow()}

limit_choices_to = limit_pub_date_choices
```

If `limit_choices_to` is or returns a [`Q object`](/ja/3.1/ref/models/querysets/#django.db.models.Q), which is useful for [complex queries](/ja/3.1/topics/db/queries/#complex-lookups-with-q), then it will only have an effect on the choices
available in the admin when the field is not listed in
[`raw_id_fields`](/ja/3.1/ref/contrib/admin/#django.contrib.admin.ModelAdmin.raw_id_fields) in the
`ModelAdmin` for the model.

> **Note**
>
> If a callable is used for `limit_choices_to`, it will be invoked
> every time a new form is instantiated. It may also be invoked when a
> model is validated, for example by management commands or the admin.
> The admin constructs querysets to validate its form inputs in various
> edge cases multiple times, so there is a possibility your callable may
> be invoked several times.

#### `ForeignKey.related_name`

The name to use for the relation from the related object back to this one.
It's also the default value for [`related_query_name`](#django.db.models.ForeignKey.related_query_name) (the name to use
for the reverse filter name from the target model). See the [related
objects documentation](/ja/3.1/topics/db/queries/#backwards-related-objects) for a full explanation
and example. Note that you must set this value when defining relations on
[abstract models](/ja/3.1/topics/db/models/#abstract-base-classes); and when you do so
[some special syntax](/ja/3.1/topics/db/models/#abstract-related-name) is available.

If you'd prefer Django not to create a backwards relation, set
`related_name` to `'+'` or end it with `'+'`. For example, this will
ensure that the `User` model won't have a backwards relation to this
model:

```
user = models.ForeignKey(
    User,
    on_delete=models.CASCADE,
    related_name='+',
)
```

#### `ForeignKey.related_query_name`

The name to use for the reverse filter name from the target model. It
defaults to the value of [`related_name`](#django.db.models.ForeignKey.related_name) or
[`default_related_name`](/ja/3.1/ref/models/options/#django.db.models.Options.default_related_name) if set, otherwise it
defaults to the name of the model:

```
# Declare the ForeignKey with related_query_name
class Tag(models.Model):
    article = models.ForeignKey(
        Article,
        on_delete=models.CASCADE,
        related_name="tags",
        related_query_name="tag",
    )
    name = models.CharField(max_length=255)

# That's now the name of the reverse filter
Article.objects.filter(tag__name="important")
```

Like [`related_name`](#django.db.models.ForeignKey.related_name), `related_query_name` supports app label and
class interpolation via [some special syntax](/ja/3.1/topics/db/models/#abstract-related-name).

#### `ForeignKey.to_field`

The field on the related object that the relation is to. By default, Django
uses the primary key of the related object. If you reference a different
field, that field must have `unique=True`.

#### `ForeignKey.db_constraint`

Controls whether or not a constraint should be created in the database for
this foreign key. The default is `True`, and that's almost certainly what
you want; setting this to `False` can be very bad for data integrity.
That said, here are some scenarios where you might want to do this:

- You have legacy data that is not valid.
- You're sharding your database.

If this is set to `False`, accessing a related object that doesn't exist
will raise its `DoesNotExist` exception.

#### `ForeignKey.swappable`

Controls the migration framework's reaction if this [`ForeignKey`](#django.db.models.ForeignKey)
is pointing at a swappable model. If it is `True` \- the default -
then if the [`ForeignKey`](#django.db.models.ForeignKey) is pointing at a model which matches
the current value of `settings.AUTH_USER_MODEL` (or another swappable
model setting) the relationship will be stored in the migration using
a reference to the setting, not to the model directly.

You only want to override this to be `False` if you are sure your
model should always point towards the swapped-in model - for example,
if it is a profile model designed specifically for your custom user model.

Setting it to `False` does not mean you can reference a swappable model
even if it is swapped out - `False` means that the migrations made
with this ForeignKey will always reference the exact model you specify
(so it will fail hard if the user tries to run with a User model you don't
support, for example).

If in doubt, leave it to its default of `True`.

### `ManyToManyField`

#### `class ManyToManyField(to, **options)`

A many-to-many relationship. Requires a positional argument: the class to
which the model is related, which works exactly the same as it does for
[`ForeignKey`](#django.db.models.ForeignKey), including [recursive](#recursive-relationships) and
[lazy](#lazy-relationships) relationships.

Related objects can be added, removed, or created with the field's
[`RelatedManager`](/ja/3.1/ref/models/relations/#django.db.models.fields.related.RelatedManager).

#### Database Representation

Behind the scenes, Django creates an intermediary join table to represent the
many-to-many relationship. By default, this table name is generated using the
name of the many-to-many field and the name of the table for the model that
contains it. Since some databases don't support table names above a certain
length, these table names will be automatically truncated and a uniqueness hash
will be used, e.g. `author_books_9cdf`. You can manually provide the name of
the join table using the [`db_table`](#django.db.models.ManyToManyField.db_table) option.

#### 引数

[`ManyToManyField`](#django.db.models.ManyToManyField) accepts an extra set of arguments -- all optional --
that control how the relationship functions.

#### `ManyToManyField.related_name`

Same as [`ForeignKey.related_name`](#django.db.models.ForeignKey.related_name).

#### `ManyToManyField.related_query_name`

Same as [`ForeignKey.related_query_name`](#django.db.models.ForeignKey.related_query_name).

#### `ManyToManyField.limit_choices_to`

Same as [`ForeignKey.limit_choices_to`](#django.db.models.ForeignKey.limit_choices_to).

`limit_choices_to` has no effect when used on a `ManyToManyField` with a
custom intermediate table specified using the
[`through`](#django.db.models.ManyToManyField.through) parameter.

#### `ManyToManyField.symmetrical`

Only used in the definition of ManyToManyFields on self. Consider the
following model:

```
from django.db import models

class Person(models.Model):
    friends = models.ManyToManyField("self")
```

When Django processes this model, it identifies that it has a
[`ManyToManyField`](#django.db.models.ManyToManyField) on itself, and as a result, it doesn't add a
`person_set` attribute to the `Person` class. Instead, the
[`ManyToManyField`](#django.db.models.ManyToManyField) is assumed to be symmetrical -- that is, if I am
your friend, then you are my friend.

If you do not want symmetry in many-to-many relationships with `self`, set
[`symmetrical`](#django.db.models.ManyToManyField.symmetrical) to `False`. This will force Django to
add the descriptor for the reverse relationship, allowing
[`ManyToManyField`](#django.db.models.ManyToManyField) relationships to be non-symmetrical.

> **Changed in Django 3.0**
>
> Specifying `symmetrical=True` for recursive many-to-many
> relationships using an intermediary model was allowed.

#### `ManyToManyField.through`

Django will automatically generate a table to manage many-to-many
relationships. However, if you want to manually specify the intermediary
table, you can use the [`through`](#django.db.models.ManyToManyField.through) option to specify
the Django model that represents the intermediate table that you want to
use.

The most common use for this option is when you want to associate
[extra data with a many-to-many relationship](/ja/3.1/topics/db/models/#intermediary-manytomany).

> **Note**
>
> If you don't want multiple associations between the same instances, add
> a [`UniqueConstraint`](/ja/3.1/ref/models/constraints/#django.db.models.UniqueConstraint) including the from and to
> fields. Django's automatically generated many-to-many tables include
> such a constraint.

> **Note**
>
> Recursive relationships using an intermediary model can't determine the
> reverse accessors names, as they would be the same. You need to set a
> [`related_name`](#django.db.models.ForeignKey.related_name) to at least one of them. If you'd
> prefer Django not to create a backwards relation, set `related_name`
> to `'+'`.

If you don't specify an explicit `through` model, there is still an
implicit `through` model class you can use to directly access the table
created to hold the association. It has three fields to link the models.

If the source and target models differ, the following fields are
generated:

- `id`: the primary key of the relation.
- `<containing_model>_id`: the `id` of the model that declares the
  `ManyToManyField`.
- `<other_model>_id`: the `id` of the model that the
  `ManyToManyField` points to.

If the `ManyToManyField` points from and to the same model, the following
fields are generated:

- `id`: the primary key of the relation.
- `from_<model>_id`: the `id` of the instance which points at the
  model (i.e. the source instance).
- `to_<model>_id`: the `id` of the instance to which the relationship
  points (i.e. the target model instance).

This class can be used to query associated records for a given model
instance like a normal model:

```
Model.m2mfield.through.objects.all()
```

#### `ManyToManyField.through_fields`

Only used when a custom intermediary model is specified. Django will
normally determine which fields of the intermediary model to use in order
to establish a many-to-many relationship automatically. However,
consider the following models:

```
from django.db import models

class Person(models.Model):
    name = models.CharField(max_length=50)

class Group(models.Model):
    name = models.CharField(max_length=128)
    members = models.ManyToManyField(
        Person,
        through='Membership',
        through_fields=('group', 'person'),
    )

class Membership(models.Model):
    group = models.ForeignKey(Group, on_delete=models.CASCADE)
    person = models.ForeignKey(Person, on_delete=models.CASCADE)
    inviter = models.ForeignKey(
        Person,
        on_delete=models.CASCADE,
        related_name="membership_invites",
    )
    invite_reason = models.CharField(max_length=64)
```

`Membership` has *two* foreign keys to `Person` (`person` and
`inviter`), which makes the relationship ambiguous and Django can't know
which one to use. In this case, you must explicitly specify which
foreign keys Django should use using `through_fields`, as in the example
above.

`through_fields` accepts a 2-tuple `('field1', 'field2')`, where
`field1` is the name of the foreign key to the model the
[`ManyToManyField`](#django.db.models.ManyToManyField) is defined on (`group` in this case), and
`field2` the name of the foreign key to the target model (`person`
in this case).

When you have more than one foreign key on an intermediary model to any
(or even both) of the models participating in a many-to-many relationship,
you *must* specify `through_fields`. This also applies to
[recursive relationships](#recursive-relationships)
when an intermediary model is used and there are more than two
foreign keys to the model, or you want to explicitly specify which two
Django should use.

#### `ManyToManyField.db_table`

The name of the table to create for storing the many-to-many data. If this
is not provided, Django will assume a default name based upon the names of:
the table for the model defining the relationship and the name of the field
itself.

#### `ManyToManyField.db_constraint`

Controls whether or not constraints should be created in the database for
the foreign keys in the intermediary table. The default is `True`, and
that's almost certainly what you want; setting this to `False` can be
very bad for data integrity. That said, here are some scenarios where you
might want to do this:

- You have legacy data that is not valid.
- You're sharding your database.

It is an error to pass both `db_constraint` and `through`.

#### `ManyToManyField.swappable`

Controls the migration framework's reaction if this [`ManyToManyField`](#django.db.models.ManyToManyField)
is pointing at a swappable model. If it is `True` \- the default -
then if the [`ManyToManyField`](#django.db.models.ManyToManyField) is pointing at a model which matches
the current value of `settings.AUTH_USER_MODEL` (or another swappable
model setting) the relationship will be stored in the migration using
a reference to the setting, not to the model directly.

You only want to override this to be `False` if you are sure your
model should always point towards the swapped-in model - for example,
if it is a profile model designed specifically for your custom user model.

If in doubt, leave it to its default of `True`.

[`ManyToManyField`](#django.db.models.ManyToManyField) does not support [`validators`](#django.db.models.Field.validators).

[`null`](#django.db.models.Field.null) has no effect since there is no way to require a
relationship at the database level.

### `OneToOneField`

#### `class OneToOneField(to, on_delete, parent_link=False, **options)`

A one-to-one relationship. Conceptually, this is similar to a
[`ForeignKey`](#django.db.models.ForeignKey) with [`unique=True`](#django.db.models.Field.unique), but the
"reverse" side of the relation will directly return a single object.

This is most useful as the primary key of a model which "extends"
another model in some way; [複数テーブルの継承](/ja/3.1/topics/db/models/#multi-table-inheritance) is
implemented by adding an implicit one-to-one relation from the child
model to the parent model, for example.

One positional argument is required: the class to which the model will be
related. This works exactly the same as it does for [`ForeignKey`](#django.db.models.ForeignKey),
including all the options regarding [recursive](#recursive-relationships)
and [lazy](#lazy-relationships) relationships.

If you do not specify the [`related_name`](#django.db.models.ForeignKey.related_name) argument for the
`OneToOneField`, Django will use the lowercase name of the current model as
default value.

With the following example:

```
from django.conf import settings
from django.db import models

class MySpecialUser(models.Model):
    user = models.OneToOneField(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
    )
    supervisor = models.OneToOneField(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name='supervisor_of',
    )
```

your resulting `User` model will have the following attributes:

```
>>> user = User.objects.get(pk=1)
>>> hasattr(user, 'myspecialuser')
True
>>> hasattr(user, 'supervisor_of')
True
```

A `RelatedObjectDoesNotExist` exception is raised when accessing the reverse
relationship if an entry in the related table doesn't exist. This is a subclass
of the target model's [`Model.DoesNotExist`](/ja/3.1/ref/models/class/#django.db.models.Model.DoesNotExist) exception. For example, if a user
doesn't have a supervisor designated by `MySpecialUser`:

```
>>> user.supervisor_of
Traceback (most recent call last):
    ...
RelatedObjectDoesNotExist: User has no supervisor_of.
```

Additionally, `OneToOneField` accepts all of the extra arguments
accepted by [`ForeignKey`](#django.db.models.ForeignKey), plus one extra argument:

#### `OneToOneField.parent_link`

When `True` and used in a model which inherits from another
[concrete model](/ja/3.1/glossary/#term-concrete-model), indicates that this field should be used as the
link back to the parent class, rather than the extra
`OneToOneField` which would normally be implicitly created by
subclassing.

See [One-to-one relationships](/ja/3.1/topics/db/examples/one_to_one/) for usage
examples of `OneToOneField`.

## Field API reference

#### `class Field`

`Field` is an abstract class that represents a database table column.
Django uses fields to create the database table ([`db_type()`](#django.db.models.Field.db_type)), to map
Python types to database ([`get_prep_value()`](#django.db.models.Field.get_prep_value)) and vice-versa
([`from_db_value()`](#django.db.models.Field.from_db_value)).

A field is thus a fundamental piece in different Django APIs, notably,
[`models`](/ja/3.1/ref/models/instances/#django.db.models.Model) and [`querysets`](/ja/3.1/ref/models/querysets/#django.db.models.query.QuerySet).

In models, a field is instantiated as a class attribute and represents a
particular table column, see [モデル](/ja/3.1/topics/db/models/). It has attributes
such as [`null`](#django.db.models.Field.null) and [`unique`](#django.db.models.Field.unique), and methods that Django uses to
map the field value to database-specific values.

A `Field` is a subclass of
[`RegisterLookupMixin`](/ja/3.1/ref/models/lookups/#django.db.models.lookups.RegisterLookupMixin) and thus both
[`Transform`](/ja/3.1/ref/models/lookups/#django.db.models.Transform) and
[`Lookup`](/ja/3.1/ref/models/lookups/#django.db.models.Lookup) can be registered on it to be used
in `QuerySet`s (e.g. `field_name__exact="foo"`). All [built-in
lookups](/ja/3.1/ref/models/querysets/#field-lookups) are registered by default.

All of Django's built-in fields, such as [`CharField`](#django.db.models.CharField), are particular
implementations of `Field`. If you need a custom field, you can either
subclass any of the built-in fields or write a `Field` from scratch. In
either case, see [カスタム model fieldsの実装](/ja/3.1/howto/custom-model-fields/).

#### `description`

A verbose description of the field, e.g. for the
[`django.contrib.admindocs`](/ja/3.1/ref/contrib/admin/admindocs/#module-django.contrib.admindocs) application.

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_class`

> **New in Django 3.0**

A class implementing the [descriptor protocol](https://docs.python.org/3/reference/datamodel.html#descriptors)
that is instantiated and assigned to the model instance attribute. The
constructor must accept a single argument, the `Field` instance.
Overriding this class attribute allows for customizing the get and set
behavior.

To map a `Field` to a database-specific type, Django exposes several
methods:

#### `get_internal_type()`

Returns a string naming this field for backend specific purposes.
By default, it returns the class name.

See [Emulating built-in field types](/ja/3.1/howto/custom-model-fields/#emulating-built-in-field-types) for usage in custom fields.

#### `db_type(connection)`

Returns the database column data type for the [`Field`](#django.db.models.Field), taking
into account the `connection`.

See [カスタムデータベースタイプ](/ja/3.1/howto/custom-model-fields/#custom-database-types) for usage in custom fields.

#### `rel_db_type(connection)`

Returns the database column data type for fields such as `ForeignKey`
and `OneToOneField` that point to the [`Field`](#django.db.models.Field), taking
into account the `connection`.

See [カスタムデータベースタイプ](/ja/3.1/howto/custom-model-fields/#custom-database-types) 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()`](#django.db.models.Field.get_db_prep_value) and [`get_prep_value()`](#django.db.models.Field.get_prep_value) are used:

#### `get_prep_value(value)`

`value` is 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](/ja/3.1/howto/custom-model-fields/#converting-python-objects-to-query-values) for usage.

#### `get_db_prep_value(value, connection, prepared=False)`

Converts `value` to a backend-specific value. By default it returns
`value` if `prepared=True` and [`get_prep_value()`](#django.db.models.Field.get_prep_value) if is
`False`.

See [Converting query values to database values](/ja/3.1/howto/custom-model-fields/#converting-query-values-to-database-values) for usage.

When loading data, [`from_db_value()`](#django.db.models.Field.from_db_value) is used:

#### `from_db_value(value, expression, connection)`

Converts a value as returned by the database to a Python object. It is
the reverse of [`get_prep_value()`](#django.db.models.Field.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.

`expression` is the same as `self`.

See [Converting values to Python objects](/ja/3.1/howto/custom-model-fields/#converting-values-to-python-objects) for usage.

> **Note**
>
> For performance reasons, `from_db_value` is not implemented as a
> no-op on fields which do not require it (all Django fields).
> Consequently you may not call `super` in your definition.

When saving, [`pre_save()`](#django.db.models.Field.pre_save) and [`get_db_prep_save()`](#django.db.models.Field.get_db_prep_save) are used:

#### `get_db_prep_save(value, connection)`

Same as the [`get_db_prep_value()`](#django.db.models.Field.get_db_prep_value), but called when the field value
must be *saved* to the database. By default returns
[`get_db_prep_value()`](#django.db.models.Field.get_db_prep_value).

#### `pre_save(model_instance, add)`

Method called prior to [`get_db_prep_save()`](#django.db.models.Field.get_db_prep_save) to prepare the value
before being saved (e.g. for [`DateField.auto_now`](#django.db.models.DateField.auto_now)).

`model_instance` is the instance this field belongs to and `add`
is whether the instance is being saved to the database for the first
time.

It should return the value of the appropriate attribute from
`model_instance` for this field. The attribute name is in
`self.attname` (this is set up by [`Field`](#django.db.models.Field)).

See [保存する前に前もって値を加工する場合](/ja/3.1/howto/custom-model-fields/#preprocessing-values-before-saving) for usage.

Fields often receive their values as a different type, either from
serialization or from forms.

#### `to_python(value)`

Converts the value into the correct Python object. It acts as the
reverse of [`value_to_string()`](#django.db.models.Field.value_to_string), and is also called in
[`clean()`](/ja/3.1/ref/models/instances/#django.db.models.Model.clean).

See [Converting values to Python objects](/ja/3.1/howto/custom-model-fields/#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)`

Returns the field's value for the given model instance.

This method is often used by [`value_to_string()`](#django.db.models.Field.value_to_string).

#### `value_to_string(obj)`

Converts `obj` to a string. Used to serialize the value of the field.

See [シリアライズするためにフィールドデータを変換する場合](/ja/3.1/howto/custom-model-fields/#converting-model-field-to-serialization) for usage.

When using [`model forms`](/ja/3.1/topics/forms/modelforms/#django.forms.ModelForm), the `Field`
needs to know which form field it should be represented by:

#### `formfield(form_class=None, choices_form_class=None, **kwargs)`

Returns the default [`django.forms.Field`](/ja/3.1/ref/forms/fields/#django.forms.Field) of this field for
[`ModelForm`](/ja/3.1/topics/forms/modelforms/#django.forms.ModelForm).

By default, if both `form_class` and `choices_form_class` are
`None`, it uses [`CharField`](/ja/3.1/ref/forms/fields/#django.forms.CharField). If the field has
[`choices`](#django.db.models.Field.choices) and `choices_form_class`
isn't specified, it uses [`TypedChoiceField`](/ja/3.1/ref/forms/fields/#django.forms.TypedChoiceField).

See [Specifying the form field for a model field](/ja/3.1/howto/custom-model-fields/#specifying-form-field-for-model-field) for usage.

#### `deconstruct()`

Returns a 4-tuple with enough information to recreate the field:

1. The name of the field on the model.
2. 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.
3. A list of positional arguments.
4. A dict of keyword arguments.

This method must be added to fields prior to 1.7 to migrate its data
using [マイグレーション](/ja/3.1/topics/migrations/).

# Field attribute reference

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](/ja/3.1/ref/models/meta/#model-meta-field-api) to narrow down a search for specific field types.
Custom model fields should implement these flags.

## Attributes for fields

#### `Field.auto_created`

Boolean flag that indicates if the field was automatically created, such
as the `OneToOneField` used by model inheritance.

#### `Field.concrete`

Boolean flag that indicates if the field has a database column associated
with it.

#### `Field.hidden`

Boolean flag that indicates if a field is used to back another non-hidden
field's functionality (e.g. the `content_type` and `object_id` fields
that make up a `GenericForeignKey`). The `hidden` flag is used to
distinguish what constitutes the public subset of fields on the model from
all the fields on the model.

> **Note**
>
> [`Options.get_fields()`](/ja/3.1/ref/models/meta/#django.db.models.options.Options.get_fields)
> excludes hidden fields by default. Pass in `include_hidden=True` to
> return hidden fields in the results.

#### `Field.is_relation`

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.model`

Returns the model on which the field is defined. If a field is defined on
a superclass of a model, `model` will refer to the superclass, not the
class of the instance.

## Attributes for fields with relations

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`](#django.db.models.Field.is_relation)).

#### `Field.many_to_many`

Boolean flag that is `True` if the field has a many-to-many relation;
`False` otherwise. The only field included with Django where this is
`True` is `ManyToManyField`.

#### `Field.many_to_one`

Boolean flag that is `True` if the field has a many-to-one relation, such
as a `ForeignKey`; `False` otherwise.

#### `Field.one_to_many`

Boolean flag that is `True` if the field has a one-to-many relation, such
as a `GenericRelation` or the reverse of a `ForeignKey`; `False`
otherwise.

#### `Field.one_to_one`

Boolean flag that is `True` if the field has a one-to-one relation, such
as a `OneToOneField`; `False` otherwise.

#### `Field.related_model`

Points to the model the field relates to. For example, `Author` in
`ForeignKey(Author, on_delete=models.CASCADE)`. The `related_model` for
a `GenericForeignKey` is always `None`.
