---
title: "モデルインスタンスリファレンス"
version: 3.2
locale: ja
source: https://docs.djangoproject.com/ja/3.2/ref/models/instances/
canonical: https://djangodocs.dev/ja/3.2/ref/models/instances/
---
# モデルインスタンスリファレンス

このドキュメントでは、`Model` API の詳細を説明しています。[モデル](/ja/3.2/topics/db/models/) と [データベースクエリ](/ja/3.2/topics/db/queries/) ガイドにある説明を前提としていますので、このドキュメントを読む前にこの 2 つを読んでおいた方がよいでしょう。

このドキュメント全体を通して、[データベースクエリガイド](/ja/3.2/topics/db/queries/) で使った [Weblog モデル例](/ja/3.2/topics/db/queries/#queryset-model-example) を使用します。

## オブジェクトを作成する

To create a new instance of a model, instantiate it like any other Python
class:

#### `class Model(**kwargs)`

The keyword arguments are the names of the fields you've defined on your model.
Note that instantiating a model in no way touches your database; for that, you
need to [`save()`](#django.db.models.Model.save).

> **Note**
>
> `__init__` メソッドをオーバーライドしてモデルをカスタマイズする誘惑に駆られるかもしれません。その場合は、とは言え、あらゆる変更がモデルインスタンスを保存しないように、呼び出しシグネチャを変更しないように配慮してください。`__init__` をオーバーライドするのではなく、以下のいずれかのアプローチを試してみてください:
>
> 1. モデルクラスにクラスメソッドを追加する:
>
>    ```
>    from django.db import models
>
>    class Book(models.Model):
>        title = models.CharField(max_length=100)
>
>        @classmethod
>        def create(cls, title):
>            book = cls(title=title)
>            # do something with the book
>            return book
>
>    book = Book.create("Pride and Prejudice")
>    ```
> 2. 独自のマネジャーにメソッドを追加する (通常推奨される方法です):
>
>    ```
>    class BookManager(models.Manager):
>        def create_book(self, title):
>            book = self.create(title=title)
>            # do something with the book
>            return book
>
>    class Book(models.Model):
>        title = models.CharField(max_length=100)
>
>        objects = BookManager()
>
>    book = Book.objects.create_book("Pride and Prejudice")
>    ```

### モデルの読み込みをカスタマイズする

#### `classmethod Model.from_db(db, field_names, values)`

`from_db()` メソッドを使うと、データベースから読み込むときのモデルインスタンス作成をカスタマイズすることができます。

引数 `db` はモデルを読み込む対象となるデータベースへのエイリアスになります、 `field_names` は読み込まれるすべてのフィールドの名前を持ち、そして `values` は `field_names` 内各フィールドに対応した値を持ちます。 `field_names` は `values` と同じ並び順になります。モデルのフィールドが全て存在する場合、 `values` はその順番が `__init__()` が期待する順番である事が保障されます。つまり、そのインスタンスは `cls(*values)` によって生成されえます。いずれかのフィールドが遅延評価されている場合、そのフィールドは `field_names` 内に出現しません。その場合、存在しない各フィールドには `django.db.models.DEFERRED` の値が設定されています。

In addition to creating the new model, the `from_db()` method must set the
`adding` and `db` flags in the new instance's [`_state`](#django.db.models.Model._state) attribute.

以下はデータベースから読みだされたフィールドの初期値をどのように保存しているのかについてを示した例です:

```
from django.db.models import DEFERRED

@classmethod
def from_db(cls, db, field_names, values):
    # Default implementation of from_db() (subject to change and could
    # be replaced with super()).
    if len(values) != len(cls._meta.concrete_fields):
        values = list(values)
        values.reverse()
        values = [
            values.pop() if f.attname in field_names else DEFERRED
            for f in cls._meta.concrete_fields
        ]
    instance = cls(*values)
    instance._state.adding = False
    instance._state.db = db
    # customization to store the original field values on the instance
    instance._loaded_values = dict(zip(field_names, values))
    return instance

def save(self, *args, **kwargs):
    # Check how the current values differ from ._loaded_values. For example,
    # prevent changing the creator_id of the model. (This example doesn't
    # support cases where 'creator_id' is deferred).
    if not self._state.adding and (
            self.creator_id != self._loaded_values['creator_id']):
        raise ValueError("Updating the value of creator isn't allowed")
    super().save(*args, **kwargs)
```

The example above shows a full `from_db()` implementation to clarify how that
is done. In this case it would be possible to use a `super()` call in the
`from_db()` method.

## データベースからオブジェクトを再読み込みする

モデルのインスタンスからあるフィールドを削除した場合、再度アクセスする事でその値をデータベースから再読み込みします:

```
>>> obj = MyModel.objects.first()
>>> del obj.field
>>> obj.field  # Loads the field from the database
```

#### `Model.refresh_from_db(using=None, fields=None)`

データベースからモデルの値を再読み込みする必要が有る場合は、 `refresh_from_db()` メソッドを利用できます。引数なしでこのメソッドを呼び出した場合は以下の処理が行われます:

1. モデル上の遅延評価されない全てのフィールドはその時点でデータベース上に存在する値に更新されます。
2. Any cached relations are cleared from the reloaded instance.

データベースからはフィールドのみが再読み込みされます。それ以外のアノテーションのようなデータベース依存の値は更新されません。いずれの [`@cached_property`](/ja/3.2/ref/utils/#django.utils.functional.cached_property) 属性等も同様にクリアされる事はありません。

再読み込みはインスタンスを読み込むデータベースから、もしくはインスタンスがデータベースから読み込まれない場合はデフォルトのデータベースから行われます。 `using` 引数は再読み込みを行うデータベースを強制的に設定する際に用いることができます。

読み込むフィールドのセットを強制的に設定するには `fields` 引数を用いる事ができます。

例えば、`update()` の呼び出しによって期待する更新が行われたかをテストするため、以下のようなテストを書くことができます:

```
def test_update_result(self):
    obj = MyModel.objects.create(val=1)
    MyModel.objects.filter(pk=obj.pk).update(val=F('val') + 1)
    # At this point obj.val is still 1, but the value in the database
    # was updated to 2. The object's updated value needs to be reloaded
    # from the database.
    obj.refresh_from_db()
    self.assertEqual(obj.val, 2)
```

遅延評価されているフィールドにアクセスした場合、その遅延評価されるフィールドの読み込みはこのメソッドを経由する事に注意してください。そのため遅延評価の読み込みがどのように行われるかを独自に設定する事が可能です。以下の例は遅延評価するフィールドが再読み込みされた時どのようにしてインスタンス上のフィールド全てを再読み込みできるかを示しています:

```
class ExampleModel(models.Model):
    def refresh_from_db(self, using=None, fields=None, **kwargs):
        # fields contains the name of the deferred field to be
        # loaded.
        if fields is not None:
            fields = set(fields)
            deferred_fields = self.get_deferred_fields()
            # If any deferred field is going to be loaded
            if fields.intersection(deferred_fields):
                # then load all of them
                fields = fields.union(deferred_fields)
        super().refresh_from_db(using, fields, **kwargs)
```

#### `Model.get_deferred_fields()`

対象となるモデルにおいて現在評価を遅延している全てのフィールドの属性名を持った集合を返すヘルパーメソッドです。

## オブジェクトを検証 (バリデーション) する

モデルのバリデーションには 3 つのステップがあります:

1. モデルフィールドを検証する - [`Model.clean_fields()`](#django.db.models.Model.clean_fields)
2. モデル全体を検証する - [`Model.clean()`](#django.db.models.Model.clean)
3. フィールドの一意性を検証する - [`Model.validate_unique()`](#django.db.models.Model.validate_unique)

モデルの [`full_clean()`](#django.db.models.Model.full_clean) メソッドを使うと、3 つ全てのステップが実行されます。

[`ModelForm`](/ja/3.2/topics/forms/modelforms/#django.forms.ModelForm) を使っているとき、[`is_valid()`](/ja/3.2/ref/forms/api/#django.forms.Form.is_valid) の呼び出しは、フォーム上に含まれる全てのフィールドに対して、これらの検証ステップを実行します。詳しくは [ModelForm ドキュメント](/ja/3.2/topics/forms/modelforms/) を参照してください。検証エラーを自分でコントロールしたい場合、もしくは [`ModelForm`](/ja/3.2/topics/forms/modelforms/#django.forms.ModelForm) から検証を必要とするフィールドを除外した場合は、モデルの [`full_clean()`](#django.db.models.Model.full_clean) メソッドだけを呼び出す必要があります。

#### `Model.full_clean(exclude=None, validate_unique=True)`

このメソッドは、[`Model.clean_fields()`](#django.db.models.Model.clean_fields)、[`Model.clean()`](#django.db.models.Model.clean)、そして [`Model.validate_unique()`](#django.db.models.Model.validate_unique) (`validate_unique` が `True` の場合) をこの順序で呼び出し、3 つ全てのステージでのエラーを含む `message_dict` 属性を持つ [`ValidationError`](/ja/3.2/ref/exceptions/#django.core.exceptions.ValidationError) を投げます。

省略可能な `exclude` 引数は、検証とクリーニングから除外するフィールド名のリストに使います。[`ModelForm`](/ja/3.2/topics/forms/modelforms/#django.forms.ModelForm) は、この引数をフォーム上に存在しないフィールドを検証対象から除外するために使います。これは、エラーが発生してもユーザーによって修正できないからです。

モデルの [`save()`](#django.db.models.Model.save) メソッドを呼んだときでも `full_clean()` は自動的に *呼ばれない* ことに注意してください。手動で作ったモデルに対して 1 ステップでモデル検証をしたいときには、手動で呼び出す必要があります。例えば:

```
from django.core.exceptions import ValidationError
try:
    article.full_clean()
except ValidationError as e:
    # Do something based on the errors contained in e.message_dict.
    # Display them to a user, or handle them programmatically.
    pass
```

`full_clean()` が行う最初のステップは、個々のフィールドをそれぞれクリーニングすることです。

#### `Model.clean_fields(exclude=None)`

このメソッドはモデル上の全てのフィールドを検証します。オプションの `exclude` 引数には検証の対象から除外したいフィールド名のリストを渡すことができます。いずれかのフィールドで検証に失敗した場合は [`ValidationError`](/ja/3.2/ref/exceptions/#django.core.exceptions.ValidationError) が送出されます。

`full_clean()` の第二段階では [`Model.clean()`](#django.db.models.Model.clean) を呼び出します。このメソッドはモデル独自のバリデーションにオーバーライドされます。

#### `Model.clean()`

このメソッドは、独自のモデルバリデーションを提供するために使い、必要な場合はモデルの属性を修正できます。例えば、フィールドに対して自動的に値を提供したり、複数のフィールドにアクセスする必要のガルバリデーションを実施できます:

```
import datetime
from django.core.exceptions import ValidationError
from django.db import models
from django.utils.translation import gettext_lazy as _

class Article(models.Model):
    ...
    def clean(self):
        # Don't allow draft entries to have a pub_date.
        if self.status == 'draft' and self.pub_date is not None:
            raise ValidationError(_('Draft entries may not have a publication date.'))
        # Set the pub_date for published items if it hasn't been set already.
        if self.status == 'published' and self.pub_date is None:
            self.pub_date = datetime.date.today()
```

ただし、[`Model.full_clean()`](#django.db.models.Model.full_clean) と同様に、モデルの `clean()` メソッドは、[`save()`](#django.db.models.Model.save) メソッドが呼ばれたときには実行されないことに注意してください。

上の例では、`Model.clean()` により発生した [`ValidationError`](/ja/3.2/ref/exceptions/#django.core.exceptions.ValidationError) 例外は文字列によりインスタンス化されていたので、特別なエラーディクショナリのキー  [`NON_FIELD_ERRORS`](/ja/3.2/ref/exceptions/#django.core.exceptions.NON_FIELD_ERRORS) に保存されます。このキーは、特定のフィールドではなくモデル全体に関連付けられたエラーに使用します:

```
from django.core.exceptions import NON_FIELD_ERRORS, ValidationError
try:
    article.full_clean()
except ValidationError as e:
    non_field_errors = e.message_dict[NON_FIELD_ERRORS]
```

例外を特定のフィールドにアサインするには、ディクショナリで [`ValidationError`](/ja/3.2/ref/exceptions/#django.core.exceptions.ValidationError) をインスタンス化し、キーにフィールド名を指定してください。上記の例を変更して、`pub_date` フィールドにエラーをアサインします:

```
class Article(models.Model):
    ...
    def clean(self):
        # Don't allow draft entries to have a pub_date.
        if self.status == 'draft' and self.pub_date is not None:
            raise ValidationError({'pub_date': _('Draft entries may not have a publication date.')})
        ...
```

`Model.clean()` 実施中に複数フィールドでエラーを発見した場合、ディクショナリを渡してエラーにフィールド名をマップすることもできます:

```
raise ValidationError({
    'title': ValidationError(_('Missing title.'), code='required'),
    'pub_date': ValidationError(_('Invalid date.'), code='invalid'),
})
```

最後に、`full_clean()` でモデル上のユニーク制限をチェックします。

> **ModelForm 内に表示されないフィールドに対してフィールド特有のバリデーションエラーを発生させる方法**
>
> (`Meta.fields` や `Meta.exclude` で制限されて) モデルフォームに表示されないフィールドに対して `Model.clean()` 内でバリデーションエラーを発生させることはできません。やろうとしても、`ValueError` が発生します。これは、バリデーションエラーが除外されたフィールドと関連付けることができないからです。
>
> このジレンマに対応するには、[`Model.clean_fields()`](#django.db.models.Model.clean_fields) をオーバーライドすることです。これはバリデーションから除外されたフィールドのリストを受け取ります。例えば:
>
> ```
> class Article(models.Model):
>     ...
>     def clean_fields(self, exclude=None):
>         super().clean_fields(exclude=exclude)
>         if self.status == 'draft' and self.pub_date is not None:
>             if exclude and 'status' in exclude:
>                 raise ValidationError(
>                     _('Draft entries may not have a publication date.')
>                 )
>             else:
>                 raise ValidationError({
>                     'status': _(
>                         'Set status to draft if there is not a '
>                         'publication date.'
>                      ),
>                 })
> ```

#### `Model.validate_unique(exclude=None)`

このメソッドは [`clean_fields()`](#django.db.models.Model.clean_fields) と似ていますが、個別のフィールドの値ではなくモデルにおけるユニーク制限を検証します。オプションの `exclude` 引数により、バリデーションから除外するフィールド名のリストを指定できます。いずれかのフィールドがバリデーションに失敗した場合、[`ValidationError`](/ja/3.2/ref/exceptions/#django.core.exceptions.ValidationError) を発生させます。

`validate_unique()` で `exclude` 引数を指定した場合、そのうちの 1 つでも含む [`unique_together`](/ja/3.2/ref/models/options/#django.db.models.Options.unique_together) 制限はチェックされません。

## オブジェクトを保存する

データベースにオブジェクトを保存し直すには、`save()` を呼び出します:

#### `Model.save(force_insert=False, force_update=False, using=DEFAULT_DB_ALIAS, update_fields=None)`

For details on using the `force_insert` and `force_update` arguments, see
[INSERT や UPDATE を強制する](#ref-models-force-insert). Details about the `update_fields` argument
can be found in the [どのフィールドを保存するか指定する](#ref-models-update-fields) section.

保存の動作をカスタマイズしたい場合は、`save()` メソッドをオーバーライドできます。詳しくは [定義済みのモデルメソッドをオーバーライドする](/ja/3.2/topics/db/models/#overriding-model-methods) を参照してください。

モデル保存のプロセスには、いくつかの細かな注意点もあります; 以下の各セクションを参照してください。

### 自動インクリメントのプライマリキー

If a model has an [`AutoField`](/ja/3.2/ref/models/fields/#django.db.models.AutoField) — an auto-incrementing
primary key — then that auto-incremented value will be calculated and saved as
an attribute on your object the first time you call `save()`:

```
>>> b2 = Blog(name='Cheddar Talk', tagline='Thoughts on cheese.')
>>> b2.id     # Returns None, because b2 doesn't have an ID yet.
>>> b2.save()
>>> b2.id     # Returns the ID of your new object.
```

There's no way to tell what the value of an ID will be before you call
`save()`, because that value is calculated by your database, not by Django.

For convenience, each model has an [`AutoField`](/ja/3.2/ref/models/fields/#django.db.models.AutoField) named
`id` by default unless you explicitly specify `primary_key=True` on a field
in your model. See the documentation for [`AutoField`](/ja/3.2/ref/models/fields/#django.db.models.AutoField)
for more details.

#### `pk` プロパティ

#### `Model.pk`

Regardless of whether you define a primary key field yourself, or let Django
supply one for you, each model will have a property called `pk`. It behaves
like a normal attribute on the model, but is actually an alias for whichever
attribute is the primary key field for the model. You can read and set this
value, just as you would for any other attribute, and it will update the
correct field in the model.

#### Explicitly specifying auto-primary-key values

If a model has an [`AutoField`](/ja/3.2/ref/models/fields/#django.db.models.AutoField) but you want to define a
new object's ID explicitly when saving, define it explicitly before saving,
rather than relying on the auto-assignment of the ID:

```
>>> b3 = Blog(id=3, name='Cheddar Talk', tagline='Thoughts on cheese.')
>>> b3.id     # Returns 3.
>>> b3.save()
>>> b3.id     # Returns 3.
```

If you assign auto-primary-key values manually, make sure not to use an
already-existing primary-key value! If you create a new object with an explicit
primary-key value that already exists in the database, Django will assume you're
changing the existing record rather than creating a new one.

Given the above `'Cheddar Talk'` blog example, this example would override the
previous record in the database:

```
b4 = Blog(id=3, name='Not Cheddar', tagline='Anything but cheese.')
b4.save()  # Overrides the previous blog with ID=3!
```

See [How Django knows to UPDATE vs. INSERT](#how-django-knows-to-update-vs-insert), below, for the reason this
happens.

Explicitly specifying auto-primary-key values is mostly useful for bulk-saving
objects, when you're confident you won't have primary-key collision.

If you're using PostgreSQL, the sequence associated with the primary key might
need to be updated; see [Manually-specifying values of auto-incrementing primary keys](/ja/3.2/ref/databases/#manually-specified-autoincrement-pk).

### What happens when you save?

When you save an object, Django performs the following steps:

1. **Emit a pre-save signal.** The [`pre_save`](/ja/3.2/ref/signals/#django.db.models.signals.pre_save)
   signal is sent, allowing any functions listening for that signal to do
   something.
2. **Preprocess the data.** Each field's
   [`pre_save()`](/ja/3.2/ref/models/fields/#django.db.models.Field.pre_save) method is called to perform any
   automated data modification that's needed. For example, the date/time fields
   override `pre_save()` to implement
   [`auto_now_add`](/ja/3.2/ref/models/fields/#django.db.models.DateField.auto_now_add) and
   [`auto_now`](/ja/3.2/ref/models/fields/#django.db.models.DateField.auto_now).
3. **Prepare the data for the database.** Each field's
   [`get_db_prep_save()`](/ja/3.2/ref/models/fields/#django.db.models.Field.get_db_prep_save) method is asked to provide
   its current value in a data type that can be written to the database.

   Most fields don't require data preparation. Simple data types, such as
   integers and strings, are 'ready to write' as a Python object. However, more
   complex data types often require some modification.

   For example, [`DateField`](/ja/3.2/ref/models/fields/#django.db.models.DateField) fields use a Python
   `datetime` object to store data. Databases don't store `datetime`
   objects, so the field value must be converted into an ISO-compliant date
   string for insertion into the database.
4. **Insert the data into the database.** The preprocessed, prepared data is
   composed into an SQL statement for insertion into the database.
5. **Emit a post-save signal.** The [`post_save`](/ja/3.2/ref/signals/#django.db.models.signals.post_save)
   signal is sent, allowing any functions listening for that signal to do
   something.

### Django が UPDATE と INSERT を見分ける方法

You may have noticed Django database objects use the same `save()` method
for creating and changing objects. Django abstracts the need to use `INSERT`
or `UPDATE` SQL statements. Specifically, when you call `save()` and the
object's primary key attribute does **not** define a
[`default`](/ja/3.2/ref/models/fields/#django.db.models.Field.default), Django follows this algorithm:

- オブジェクトのプライマリキー属性が `True` と評価される値にセットされている場合 (例えば  `None` や空の文字列以外の場合)。Django は `UPDATE` を実行します。
- If the object's primary key attribute is *not* set or if the `UPDATE`
  didn't update anything (e.g. if primary key is set to a value that doesn't
  exist in the database), Django executes an `INSERT`.

If the object's primary key attribute defines a
[`default`](/ja/3.2/ref/models/fields/#django.db.models.Field.default) then Django executes an `UPDATE` if
it is an existing model instance and primary key is set to a value that exists
in the database. Otherwise, Django executes an `INSERT`.

ここで重要なのは、そのプライマリキーが使われていないことが保証できない場合、新しいオブジェクトを保存するときに明示的にプライマリキーの値を指定しないように気をつけることです。このニュアンスについては、上述の [自動プライマリキーの値を明示的に指定する](#forcing-an-insert-or-update) と下記の [INSERT や UPDATE を強制する](#forcing-an-insert-or-update) を参照してください。

In Django 1.5 and earlier, Django did a `SELECT` when the primary key
attribute was set. If the `SELECT` found a row, then Django did an `UPDATE`,
otherwise it did an `INSERT`. The old algorithm results in one more query in
the `UPDATE` case. There are some rare cases where the database doesn't
report that a row was updated even if the database contains a row for the
object's primary key value. An example is the PostgreSQL `ON UPDATE` trigger
which returns `NULL`. In such cases it is possible to revert to the old
algorithm by setting the [`select_on_save`](/ja/3.2/ref/models/options/#django.db.models.Options.select_on_save)
option to `True`.

#### INSERT や UPDATE を強制する

In some rare circumstances, it's necessary to be able to force the
[`save()`](#django.db.models.Model.save) method to perform an SQL `INSERT` and not fall back to
doing an `UPDATE`. Or vice-versa: update, if possible, but not insert a new
row. In these cases you can pass the `force_insert=True` or
`force_update=True` parameters to the [`save()`](#django.db.models.Model.save) method.
Passing both parameters is an error: you cannot both insert *and* update at the
same time!

これらのパラメータを必要とするのは、まれであるべきです。Django は、ほとんどの場合で正しく処理を行い、オーバーライドしようとすると追跡が難しいエラーの原因となります。この機能は応用的な場合のみに使用してください。

`update_fields` を使うと `force_update` と同じように更新を強制します。

### 既存のフィールドに基づいて属性を更新する

Sometimes you'll need to perform a simple arithmetic task on a field, such
as incrementing or decrementing the current value. One way of achieving this is
doing the arithmetic in Python like:

```
>>> product = Product.objects.get(name='Venezuelan Beaver Cheese')
>>> product.number_sold += 1
>>> product.save()
```

データベースから取得した古い `number_sold` の値は 10 でした。そして、11 という値がデータベースに書き直されます。

このプロセスは、新しい値の明示的な割り当てではなく、元のフィールド値に対する更新を表現することによって、[競合状態を回避しながら](/ja/3.2/ref/models/expressions/#avoiding-race-conditions-using-f) 堅牢にすることができます。 Djangoは、このような相対的な更新を行うための [`F expressions`](/ja/3.2/ref/models/expressions/#django.db.models.F) を提供しています。 [`F expressions`](/ja/3.2/ref/models/expressions/#django.db.models.F) を使用すると、上の例は以下のように表されます:

```
>>> from django.db.models import F
>>> product = Product.objects.get(name='Venezuelan Beaver Cheese')
>>> product.number_sold = F('number_sold') + 1
>>> product.save()
```

詳しくは、[`F expressions`](/ja/3.2/ref/models/expressions/#django.db.models.F) とこれに対する [更新クエリ内で使う](/ja/3.2/topics/db/queries/#topics-db-queries-update) を参照してください。

### どのフィールドを保存するか指定する

`save()` にキーワード引数 `update_fields` 内でフィールドリストの名前が渡された場合、このリスト内で指定されたフィールドだけが更新されます。これは、オブジェクトの 1 つないし少数のフィールドだけを更新したい場合に望ましいでしょう。データベースで全てのモデルフィールドを更新しないようにすると、実行速度が少し向上します。例えば:

```
product.name = 'Name changed again'
product.save(update_fields=['name'])
```

The `update_fields` argument can be any iterable containing strings. An
empty `update_fields` iterable will skip the save. A value of `None` will
perform an update on all fields.

`update_fields` を指定すると更新を強制します。

遅延モデルローディング ([`only()`](/ja/3.2/ref/models/querysets/#django.db.models.query.QuerySet.only) や [`defer()`](/ja/3.2/ref/models/querysets/#django.db.models.query.QuerySet.defer)) を通してフェッチされたモデルを保存するとき、DB からロードされたフィールドだけが更新されます。実際には、このケースでは自動的な `update_fields` が存在します。遅延フィールドの値を追加もしくは変更した場合、フィールドは更新されたフィールドに追加されます。

## オブジェクトを削除する

#### `Model.delete(using=DEFAULT_DB_ALIAS, keep_parents=False)`

オブジェクトに対して SQL `DELETE` を発行します。これはデータベースでオブジェクトの削除のみを行います; Python のインスタンスはなお存在しまたフィールド内にデータを持ち続けます。このメソッドは削除されるオブジェクトの数とオブジェクトタイプごとの削除の数のディクショナリを返します。

より詳しく (まとめてオブジェクトを削除する方法を含む) については、[オブジェクトを削除する](/ja/3.2/topics/db/queries/#topics-db-queries-delete) を参照してください。

独自の削除動作がほしいときは、`delete()` メソッドをオーバーライドすることができます。詳しくは [定義済みのモデルメソッドをオーバーライドする](/ja/3.2/topics/db/models/#overriding-model-methods) を参照してください。

Sometimes with [multi-table inheritance](/ja/3.2/topics/db/models/#multi-table-inheritance) you may
want to delete only a child model's data. Specifying `keep_parents=True` will
keep the parent model's data.

## Pickling objects

When you [`pickle`](https://docs.python.org/3/library/pickle.html#module-pickle) a model, its current state is pickled. When you unpickle
it, it'll contain the model instance at the moment it was pickled, rather than
the data that's currently in the database.

> **You can't share pickles between versions**
>
> Pickles of models are only valid for the version of Django that
> was used to generate them. If you generate a pickle using Django
> version N, there is no guarantee that pickle will be readable with
> Django version N+1. Pickles should not be used as part of a long-term
> archival strategy.
>
> Since pickle compatibility errors can be difficult to diagnose, such as
> silently corrupted objects, a `RuntimeWarning` is raised when you try to
> unpickle a model in a Django version that is different than the one in
> which it was pickled.

## Other model instance methods

A few object methods have special purposes.

### `__str__()`

#### `Model.__str__()`

The `__str__()` method is called whenever you call `str()` on an object.
Django uses `str(obj)` in a number of places. Most notably, to display an
object in the Django admin site and as the value inserted into a template when
it displays an object. Thus, you should always return a nice, human-readable
representation of the model from the `__str__()` method.

例:

```
from django.db import models

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

    def __str__(self):
        return '%s %s' % (self.first_name, self.last_name)
```

### `__eq__()`

#### `Model.__eq__()`

The equality method is defined such that instances with the same primary
key value and the same concrete class are considered equal, except that
instances with a primary key value of `None` aren't equal to anything except
themselves. For proxy models, concrete class is defined as the model's first
non-proxy parent; for all other models it's simply the model's class.

例:

```
from django.db import models

class MyModel(models.Model):
    id = models.AutoField(primary_key=True)

class MyProxyModel(MyModel):
    class Meta:
        proxy = True

class MultitableInherited(MyModel):
    pass

# Primary keys compared
MyModel(id=1) == MyModel(id=1)
MyModel(id=1) != MyModel(id=2)
# Primary keys are None
MyModel(id=None) != MyModel(id=None)
# Same instance
instance = MyModel(id=None)
instance == instance
# Proxy model
MyModel(id=1) == MyProxyModel(id=1)
# Multi-table inheritance
MyModel(id=1) != MultitableInherited(id=1)
```

### `__hash__()`

#### `Model.__hash__()`

The `__hash__()` method is based on the instance's primary key value. It
is effectively `hash(obj.pk)`. If the instance doesn't have a primary key
value then a `TypeError` will be raised (otherwise the `__hash__()`
method would return different values before and after the instance is
saved, but changing the [`__hash__()`](https://docs.python.org/3/reference/datamodel.html#object.__hash__) value of an instance is
forbidden in Python.

### `get_absolute_url()`

#### `Model.get_absolute_url()`

オブジェクトに対する正式な URL を計算する方法は、`get_absolute_url()` で定義します。呼び出し元に対して、このメソッドは文字列を返します。この文字列は HTTP を通じてオブジェクトを参照するために使えるものです。

例:

```
def get_absolute_url(self):
    return "/people/%i/" % self.id
```

このコードは正しくかつシンプルですが、この種のメソッドを記述するのに最も適した方法です。[`reverse()`](/ja/3.2/ref/urlresolvers/#django.urls.reverse) 関数が一般的にベストアプローチとなります。

例:

```
def get_absolute_url(self):
    from django.urls import reverse
    return reverse('people-detail', kwargs={'pk' : self.pk})
```

Django が `get_absolute_url()` を使う場所の一つが、admin アプリです。オブジェクトにこのメソッドが定義されている場合、オブジェクト編集のページは "View on site" リンクを持つようになり、`get_absolute_url()` で定義された通りオブジェクトの公開用ビューに直接飛べるようになります。

同様に、Django の他にもいくつか、`get_absolute_url()` が定義されている場合に使用するものがあります ([syndication feed framework](/ja/3.2/ref/contrib/syndication/) など)。 各モデルインスタンスがユニークな URL を持つことが適切な場合、`get_absolute_url()` を定義すべきです。

> **Warning**
>
> リダイレクトポイズニングの可能性を減らすため、検証されていないユーザーの入力を利用した URL の生成は避けてください。
>
> ```
> def get_absolute_url(self):
>     return '/%s/' % self.name
> ```
>
> `self.name` が `'/example.com'` の場合、上記は `'//example.com/'` を返します。これは有効な schema relative URL ですが、期待されていた `'/%2Fexample.com/'` ではありません。

テンプレート内で、ハードコーディングしたオブジェクトの URL ではなく `get_absolute_url()` を使うのは良い実装方法です。以下のテンプレートコードは悪い例です:

```html+django
<!-- BAD template code. Avoid! -->
<a href="/people/{{ object.id }}/">{{ object.name }}</a>
```

以下のテンプレートコードは改善例です:

```html+django
<a href="{{ object.get_absolute_url }}">{{ object.name }}</a>
```

The logic here is that if you change the URL structure of your objects, even
for something small like correcting a spelling error, you don't want to have to
track down every place that the URL might be created. Specify it once, in
`get_absolute_url()` and have all your other code call that one place.

> **Note**
>
> The string you return from `get_absolute_url()` **must** contain only
> ASCII characters (required by the URI specification, [**RFC 2396 Section 2**](https://datatracker.ietf.org/doc/html/rfc2396.html#section-2))
> and be URL-encoded, if necessary.
>
> Code and templates calling `get_absolute_url()` should be able to use the
> result directly without any further processing. You may wish to use the
> `django.utils.encoding.iri_to_uri()` function to help with this if you
> are using strings containing characters outside the ASCII range.

## Extra instance methods

In addition to [`save()`](#django.db.models.Model.save), [`delete()`](#django.db.models.Model.delete), a model object
might have some of the following methods:

#### `Model.get_FOO_display()`

For every field that has [`choices`](/ja/3.2/ref/models/fields/#django.db.models.Field.choices) set, the
object will have a `get_FOO_display()` method, where `FOO` is the name of
the field. This method returns the "human-readable" value of the field.

例:

```
from django.db import models

class Person(models.Model):
    SHIRT_SIZES = (
        ('S', 'Small'),
        ('M', 'Medium'),
        ('L', 'Large'),
    )
    name = models.CharField(max_length=60)
    shirt_size = models.CharField(max_length=2, choices=SHIRT_SIZES)
```

```
>>> p = Person(name="Fred Flintstone", shirt_size="L")
>>> p.save()
>>> p.shirt_size
'L'
>>> p.get_shirt_size_display()
'Large'
```

> **Changed in Django 3.1**
>
> Support for [`ArrayField`](/ja/3.2/ref/contrib/postgres/fields/#django.contrib.postgres.fields.ArrayField) and
> [`RangeField`](/ja/3.2/ref/contrib/postgres/fields/#django.contrib.postgres.fields.RangeField) was added.

#### `Model.get_next_by_FOO(**kwargs)`

#### `Model.get_previous_by_FOO(**kwargs)`

For every [`DateField`](/ja/3.2/ref/models/fields/#django.db.models.DateField) and
[`DateTimeField`](/ja/3.2/ref/models/fields/#django.db.models.DateTimeField) that does not have [`null=True`](/ja/3.2/ref/models/fields/#django.db.models.Field.null), the object will have `get_next_by_FOO()` and
`get_previous_by_FOO()` methods, where `FOO` is the name of the field. This
returns the next and previous object with respect to the date field, raising
a [`DoesNotExist`](/ja/3.2/ref/models/class/#django.db.models.Model.DoesNotExist) exception when appropriate.

Both of these methods will perform their queries using the default
manager for the model. If you need to emulate filtering used by a
custom manager, or want to perform one-off custom filtering, both
methods also accept optional keyword arguments, which should be in the
format described in [Field lookups](/ja/3.2/ref/models/querysets/#field-lookups).

Note that in the case of identical date values, these methods will use the
primary key as a tie-breaker. This guarantees that no records are skipped or
duplicated. That also means you cannot use those methods on unsaved objects.

> **Overriding extra instance methods**
>
> In most cases overriding or inheriting `get_FOO_display()`,
> `get_next_by_FOO()`, and `get_previous_by_FOO()` should work as
> expected. Since they are added by the metaclass however, it is not
> practical to account for all possible inheritance structures. In more
> complex cases you should override `Field.contribute_to_class()` to set
> the methods you need.

## Other attributes

### `_state`

#### `Model._state`

The `_state` attribute refers to a `ModelState` object that tracks
the lifecycle of the model instance.

The `ModelState` object has two attributes: `adding`, a flag which is
`True` if the model has not been saved to the database yet, and `db`,
a string referring to the database alias the instance was loaded from or
saved to.

Newly instantiated instances have `adding=True` and `db=None`,
since they are yet to be saved. Instances fetched from a `QuerySet`
will have `adding=False` and `db` set to the alias of the associated
database.
