---
title: "カスタムのモデルフィールドを作成する"
version: 4.2
locale: ja
source: https://docs.djangoproject.com/ja/4.2/howto/custom-model-fields/
canonical: https://djangodocs.dev/ja/4.2/howto/custom-model-fields/
---
# カスタムのモデルフィールドを作成する

## はじめに

[モデルリファレンス](/ja/4.2/topics/db/models/) ドキュメントでは、Djangoの標準フィールドクラスである、 [`CharField`](/ja/4.2/ref/models/fields/#django.db.models.CharField) や、 [`DateField`](/ja/4.2/ref/models/fields/#django.db.models.DateField) などの使い方を説明しています。多くの場合、これらのクラスがあれば十分です。ただし、Djangoのバージョンが正確な要件を満たしていない場合や、Djangoに同梱されているものとはまったく異なるフィールドを使用したい場合があります。

Django の組み込みフィールド型は、データベースで利用可能な全てのカラム型をカバーしているわけではなく、 `VARCHAR` や `INTEGER` のような一般的な型のみに対応しています。地理的な多角形や [PostgreSQL カスタム型](https://www.postgresql.org/docs/current/sql-createtype.html) のようなユーザが作成した型など、より曖昧なカラム型については、独自の Django `Field` サブクラスを定義することができます。

あるいは、複雑な Python オブジェクトを、標準的なデータベースのカラム型に合うようにシリアライズすることもできます。これもまた、`Field` サブクラスがオブジェクトをモデルで使用するのに役立つケースです。

### 私たちのサンプルオブジェクト

カスタムフィールドを作成するには、細部に少し注意する必要があります。わかりやすくなるように、このドキュメントでは「ブリッジの手札のやり取りを表すPythonオブジェクトの実装」を一貫した例として説明することにします。なお、この実装例を理解するために、ブリッジのプレイルールを理解する必要はありません。52枚のカードが、伝統的に *北* 、 *東* 、 *南* および *西* と呼ばれる4人のプレイヤーに均等に配られることだけを覚えておいてください。クラスは以下のように実装します:

```
class Hand:
    """A hand of cards (bridge style)"""

    def __init__(self, north, east, south, west):
        # Input parameters are lists of cards ('Ah', '9s', etc.)
        self.north = north
        self.east = east
        self.south = south
        self.west = west

    # ... (other possibly useful methods omitted) ...
```

これはDjangoの仕様を使っていない、普通のPythonクラスです。モデルでこれと同じようなことを実行できるようにしたいと思います（モデルの中の `hand` 属性は `Hand` インスタンスだと想定しています）

```
example = MyModel.objects.get(pk=1)
print(example.hand.north)

new_hand = Hand(north, east, south, west)
example.hand = new_hand
example.save()
```

他のPythonクラスと同様に、モデルの `hand` 属性に割り当てたり、そこから取得したりします。コツは、そのようなオブジェクトの保存と読み込みの処理方法をDjangoに伝えることです。

モデルで `Hand` クラスを使用するために、**このクラスを変更する必要はありません**。 これは、ソースコードを変更できない既存のクラスのモデルサポートを簡単に記述できるため、理想的です。

> **Note**
>
> 例えば文字列や浮動小数点数のような、Pythonの標準的な型としてカスタムデータベースのカラム型を扱い、データを利用したいこともあります。このケースは `Hand` の例と似ているので、違いを後で説明することにします。

## 背景理論

### データベースストレージ

モデルフィールドから始めましょう。分解すると、モデルフィールドは通常のPythonオブジェクト - 文字列、ブール値、 `datetime` 、あるいは `Hand` のような複雑なもの - を、データベースを扱うときに便利な形式に変換する方法を提供します。(このような形式はシリアライズの際にも便利ですが、後で説明するように、データベース側を制御できるようになれば、その方が簡単です)。

モデルのフィールドは、既存のデータベースのカラムの型に適合するように何らかの方法で変換されなければなりません。データベースによって有効なカラム型のセットは異なりますが、利用できる型が決まっているという決まりは同じです。データベースに保存したいものはすべて、これらの型のいずれかに適合しなければなりません。

通常、特定のデータベースの列タイプに一致するようにDjangoフィールドを作成するか、データを文字列などに変換する方法が必要になります。

`Hand` の例では、すべてのカードをあらかじめ決められた順序で連結することで、カードデータを104文字の文字列に変換できます。たとえば、すべての *北* カード、次に *東* 、 *南* および *西* カードです。 したがって、`Hand` オブジェクトをデータベースのテキストまたは文字列に保存できます。

### フィールドクラスが行うこと

Djangoのすべてのフィールド（およびこのドキュメントで *fields* と言うときは、常に [form fields](/ja/4.2/ref/forms/fields/) ではなくモデルフィールドを意味します）は [`django.db.models.Field`](/ja/4.2/ref/models/fields/#django.db.models.Field) のサブクラスです。 Djangoがフィールドについて記録する情報のほとんどは、名前、ヘルプテキスト、一意性など、すべてのフィールドに共通です。 すべての情報を保存することは `Field` によって処理されます。 `Field` ができることの詳細については、後で詳しく説明します。 とりあえず、すべてが `Field` から派生し、クラスの動作の重要な部分をカスタマイズすると言うだけで十分です。

Djangoフィールドクラスは、モデル属性に格納されているものではないことを理解することが重要です。 モデル属性には通常のPythonオブジェクトが含まれます。 モデルで定義するフィールドクラスは、モデルクラスが作成されるときに実際に `Meta` クラスに保存されます（これを行う方法の正確な詳細はここでは重要ではありません）。 これは、属性を作成および変更するだけの場合、フィールドクラスは必要ないためです。 代わりに、属性値とデータベースに保存されているもの、または [serializer](/ja/4.2/topics/serialization/) に送信されるものとの間で変換するための機構を提供します。

独自のカスタムフィールドを作成する場合は、このことに留意してください。 作成するDjangoの `Field` サブクラスは、Pythonインスタンスとデータベース/シリアライザーの値をさまざまな方法で変換するための機構を提供します（たとえば、値の保存とルックアップでの値の使用には違いがあります）。 これが少しトリッキーに聞こえる場合でも、心配しないでください。以下の例で明らかになります。 カスタムフィールドが必要な場合、しばしば2つのクラスを作成することになります:

- 最初のクラスは、ユーザーが操作するPythonオブジェクトです。彼らはそれをモデル属性に割り当て、そのようなものを表示するためにそれから読み込みます。これは、この例の `Hand` クラスです。
- 2番目のクラスは `Field` サブクラスです。これは、最初のクラスを永続ストレージ形式とPython形式の間で変換する方法を知っているクラスです。

## フィールドサブクラスを書く

class:~django.db.models.Field のサブクラス化を考える前に、まず、新しいフィールドが、既存のどの [`Field`](/ja/4.2/ref/models/fields/#django.db.models.Field) クラスに最も似ているかを考えてください。既存の Django フィールドをサブクラス化して、手間を省くことはできませんか？そうでなければ、すべてのフィールドの基底となる、 [`Field`](/ja/4.2/ref/models/fields/#django.db.models.Field) クラスをサブクラス化すべきです。

新しいフィールドの初期化は、ケース固有の引数を共通の引数から分離し、後者を [`Field`](/ja/4.2/ref/models/fields/#django.db.models.Field) の `__init__()` メソッドに渡すことです。 （または親クラスに対して）。

この例では `HandField` を呼び出しています。（ [`Field`](/ja/4.2/ref/models/fields/#django.db.models.Field) サブクラス `<Something>Field` と名付けることをオススメします。 [`Field`](/ja/4.2/ref/models/fields/#django.db.models.Field) サブクラスであることが簡単にわかるためです）
既存のフィールドのようには動作しないため、この例では [`Field`](/ja/4.2/ref/models/fields/#django.db.models.Field) から直接サブクラス化しています。

```
from django.db import models

class HandField(models.Field):
    description = "A hand of cards (bridge style)"

    def __init__(self, *args, **kwargs):
        kwargs["max_length"] = 104
        super().__init__(*args, **kwargs)
```

Our `HandField` accepts most of the standard field options (see the list
below), but we ensure it has a fixed length, since it only needs to hold 52
card values plus their suits; 104 characters in total.

> **Note**
>
> 多くのDjangoのモデルフィールドは、受け取ってもなにも起こらないオプションを受け取ります。例えば、 [`editable`](/ja/4.2/ref/models/fields/#django.db.models.Field.editable) と [`auto_now`](/ja/4.2/ref/models/fields/#django.db.models.DateField.auto_now) は [`django.db.models.DateField`](/ja/4.2/ref/models/fields/#django.db.models.DateField) に渡すことができますが、 [`editable`](/ja/4.2/ref/models/fields/#django.db.models.Field.editable) のパラメーターを無視します。（ [`auto_now`](/ja/4.2/ref/models/fields/#django.db.models.DateField.auto_now) には `editable=False` がセットされています）この場合、エラーは発生しません。
>
> この振る舞いはフィールドクラスをシンプルにします。なぜなら、必要のないオプションをチェックする必要がないからです。すべてのオプションを親クラスに渡し、オプションを使用しないのです。フィールドにより厳密にオプションを扱ってほしいのか、より柔軟なカレントフィールドの動作を使うのかは、使う人次第です。

The `Field.__init__()` method takes the following parameters:

- [`verbose_name`](/ja/4.2/ref/models/fields/#django.db.models.Field.verbose_name)
- `name`
- [`primary_key`](/ja/4.2/ref/models/fields/#django.db.models.Field.primary_key)
- [`max_length`](/ja/4.2/ref/models/fields/#django.db.models.CharField.max_length)
- [`unique`](/ja/4.2/ref/models/fields/#django.db.models.Field.unique)
- [`blank`](/ja/4.2/ref/models/fields/#django.db.models.Field.blank)
- [`null`](/ja/4.2/ref/models/fields/#django.db.models.Field.null)
- [`db_index`](/ja/4.2/ref/models/fields/#django.db.models.Field.db_index)
- `rel`: 関連フィールドに使用される ([`ForeignKey`](/ja/4.2/ref/models/fields/#django.db.models.ForeignKey) など)。上級者向けです。
- [`default`](/ja/4.2/ref/models/fields/#django.db.models.Field.default)
- [`editable`](/ja/4.2/ref/models/fields/#django.db.models.Field.editable)
- `serialize`: `False` の場合、Django の [serializers](/ja/4.2/topics/serialization/) にモデルが渡されたときに、フィールドをシリアライズしません。デフォルトの値は `True` です。
- [`unique_for_date`](/ja/4.2/ref/models/fields/#django.db.models.Field.unique_for_date)
- [`unique_for_month`](/ja/4.2/ref/models/fields/#django.db.models.Field.unique_for_month)
- [`unique_for_year`](/ja/4.2/ref/models/fields/#django.db.models.Field.unique_for_year)
- [`choices`](/ja/4.2/ref/models/fields/#django.db.models.Field.choices)
- [`help_text`](/ja/4.2/ref/models/fields/#django.db.models.Field.help_text)
- [`db_column`](/ja/4.2/ref/models/fields/#django.db.models.Field.db_column)
- もしバックエンドが [tablespaces](/ja/4.2/topics/db/tablespaces/) をサポートする場合、[`db_tablespace`](/ja/4.2/ref/models/fields/#django.db.models.Field.db_tablespace): はインデックスの作成のみ行います。通常、このオプションは無視できます。
- モデル継承で使用される [`OneToOneField`](/ja/4.2/ref/models/fields/#django.db.models.OneToOneField) のように、フィールドが自動的に作成された場合は、[`auto_created`](/ja/4.2/ref/models/fields/#django.db.models.Field.auto_created) は `True` です。 高度な使用向けです。

上記のリストに説明のないオプションはすべて、通常のDjangoフィールドと同じ意味を持ちます。例と詳細については、 [field documentation](/ja/4.2/ref/models/fields/) を参照してください。

### フィールドの解体

`__init__()` メソッドとは対照的なものとして、``~.Field.deconstruct`メソッドがあります。これは:doc:`model migrations`` 中に使用されるもので、新しいフィールドのインスタンスを取得する方法、インスタンスをどのようにシリアル化して減らすかの方法をDjangoに指示します。特に、インスタンスを再生成するためにどの引数を\`\`\_\_init\_\_()\`\`に渡すかを指示します。

継承元のフィールドの上に追加のオプションを追加していない場合、新しい `deconstruct()` メソッドを記述する必要はありません。 ただし、`__init__()` で渡される引数を変更する場合（`HandField` のように）、渡される値を補足する必要があります。

`deconstruct()` 関数は4つのアイテムを含むタプルを返します。それは、フィールドの属性、インポートするフィールドクラスのフルパス、位置引数（リスト型）、キーワード引数（辞書型）です。
この関数は `deconstruct()` メソッドとは異なることに注意してください。 `deconstruct()` メソッドは [for custom classes](/ja/4.2/topics/migrations/#custom-deconstruct-method) で、3つのアイテムを含むタプルを返します。

カスタムフィールドの作成者は、最初の2つの値を気にする必要はありません。 ベース `Field` クラスには、フィールドの属性名とインポートパスを計算するためのすべてのコードがあります。 ただし、位置引数とキーワード引数は、変更する可能性が高いため、注意する必要があります。

たとえば、 `HandField` クラスでは、常に `__init__()` でmax\_lengthを強制的に設定しています。 `Field` ベースクラスの `deconstruct()` メソッドはこれを見て、キーワード引数でそれを返そうとします。 したがって、読みやすくするためにキーワード引数から削除できます:

```
from django.db import models

class HandField(models.Field):
    def __init__(self, *args, **kwargs):
        kwargs["max_length"] = 104
        super().__init__(*args, **kwargs)

    def deconstruct(self):
        name, path, args, kwargs = super().deconstruct()
        del kwargs["max_length"]
        return name, path, args, kwargs
```

新しいキーワード引数を追加する場合、自分で `kwargs` に値を設定する `deconstruct()` でコードを記述する必要があります。 また、デフォルト値が使用されている場合など、フィールドの状態を再構築する必要がない場合は、`kwargs` から値を省略してください:

```
from django.db import models

class CommaSepField(models.Field):
    "Implements comma-separated storage of lists"

    def __init__(self, separator=",", *args, **kwargs):
        self.separator = separator
        super().__init__(*args, **kwargs)

    def deconstruct(self):
        name, path, args, kwargs = super().deconstruct()
        # Only include kwarg if it's not the default
        if self.separator != ",":
            kwargs["separator"] = self.separator
        return name, path, args, kwargs
```

より複雑な例はこのドキュメントの範囲外ですが、これだけは覚えておいてください - `deconstruct()` は、フィールドインスタンスのどのような設定に対しても、その状態を再構築するために `__init__` に渡す引数を返さなければなりません。

`Field` スーパークラス内の引数に新しいデフォルト値を設定する場合には、特に注意してください。古いデフォルト値を使うと消えるようにするのではなく、デフォルト値が常に含まれるようにしてください。

また、値を位置引数として返さないようにしてください。 可能な限り、将来の互換性を最大限にするために、キーワード引数として値を返してください。コンストラクタの引数リストにおける位置よりも、頻繁に引数の名前を変更する場合、位置引数で指定しがちになるかもしれません。しかし、利用者はかなり長期間（おそらく何年も）にわたって、シリアル化されたバージョンからフィールドを再構築することに注意してください。これはバージョンのライフサイクルの長さにも依存します。

フィールドを含む移行を調べることで分解の結果を確認できます。フィールドを分解して再構築することで、単体テストで分解をテストできます:

```
name, path, args, kwargs = my_field_instance.deconstruct()
new_instance = MyField(*args, **kwargs)
self.assertEqual(my_field_instance.some_attribute, new_instance.some_attribute)
```

### データベースのカラム定義に影響しないフィールド属性

> **New in Django 4.1**

`Field.non_db_attrs` をオーバーライドすることで、カラム定義に影響しないフィールドの属性をカスタマイズできます。これはモデルのマイグレーションの間に使われ、no-opの `AlterField` 操作を検出します。

例えば:

```
class CommaSepField(models.Field):
    @property
    def non_db_attrs(self):
        return super().non_db_attrs + ("separator",)
```

### カスタムフィールドのベースクラスを変更する

Djangoは変更を検出して移行を行わないため、カスタムフィールドの基本クラスを変更することはできません。たとえば、次で始まる場合:

```
class CustomCharField(models.CharField):
    ...
```

そして、代わりに `TextField` を使用することに決めた場合、サブクラスを次のように変更することはできません:

```
class CustomCharField(models.TextField):
    ...
```

代わりに、新しいカスタムフィールドクラスを作成し、モデルを更新してそれを参照する必要があります:

```
class CustomCharField(models.CharField):
    ...

class CustomTextField(models.TextField):
    ...
```

As discussed in [removing fields](/ja/4.2/topics/migrations/#migrations-removing-model-fields), you
must retain the original `CustomCharField` class as long as you have
migrations that reference it.

### カスタムフィールドのドキュメントを書く

いつものように、フィールドタイプのドキュメントを作成し、それがどんなものかをユーザがわかるようにしましょう。開発者にとって便利な docstring を提供するだけでなく、 django.contrib.admindocs \` アプリケーションを通して、管理者アプリのユーザにフィールドタイプの短い説明を表示することもできます。これを行うには、カスタムフィールドの :attr:\`~Field.description クラス属性に説明文を記述します。上記の例では、 `admindocs` アプリケーションが表示する `HandField` の説明は 'A hand of cards (bridge style)' （日本語で「手札(ブリッジスタイル)」の意）となります。

[`django.contrib.admindocs`](/ja/4.2/ref/contrib/admin/admindocs/#module-django.contrib.admindocs) の表示では、フィールドの説明は `field.__dict__` によって補完され、説明文にフィールドの引数を組み込むことができます。例えば、 [`CharField`](/ja/4.2/ref/models/fields/#django.db.models.CharField) の説明は次のようになります:

```
description = _("String (up to %(max_length)s)")
```

### 便利なメソッド

 [`Field`](/ja/4.2/ref/models/fields/#django.db.models.Field) サブクラスを作成したら、フィールドの動作に応じて、いくつかの標準メソッドをオーバーライドすることを検討できます。以下のメソッドのリストは、おおよそ重要度の高いものから順に並んでいるので、上から始めてください。

#### カスタムデータベースタイプ

`mytype` というPostgreSQLのカスタム型を作成したとします。このとき、 `Field` をサブクラス化し、 [`db_type()`](/ja/4.2/ref/models/fields/#django.db.models.Field.db_type) 関数を以下のように実装できます:

```
from django.db import models

class MytypeField(models.Field):
    def db_type(self, connection):
        return "mytype"
```

`MytypeField` を取得したら、他の\`\`Field\`\` タイプと同様に、どのモデルでも使用できます:

```
class Person(models.Model):
    name = models.CharField(max_length=80)
    something_else = MytypeField()
```

データベースに依存しないアプリケーションを構築することを目指している場合、データベースカラムの型の違いを考慮する必要があります。たとえば、PostgreSQL の日付や時刻のカラムの型は `timestamp` と呼ばれますが、同じカラムが MySQL では `datetime` と呼ばれます。この違いは [`db_type()`](/ja/4.2/ref/models/fields/#django.db.models.Field.db_type) メソッド内で `connection.vendor` 属性をチェックすることでハンドリングできます。現在のビルトインされているベンダー名は、`sqlite`、`postgresql`、`mysql`、`oracle` です。

例えば:

```
class MyDateField(models.Field):
    def db_type(self, connection):
        if connection.vendor == "mysql":
            return "datetime"
        else:
            return "timestamp"
```

The [`db_type()`](/ja/4.2/ref/models/fields/#django.db.models.Field.db_type) and [`rel_db_type()`](/ja/4.2/ref/models/fields/#django.db.models.Field.rel_db_type) methods are called by
Django when the framework constructs the `CREATE TABLE` statements for your
application -- that is, when you first create your tables. The methods are also
called when constructing a `WHERE` clause that includes the model field --
that is, when you retrieve data using QuerySet methods like `get()`,
`filter()`, and `exclude()` and have the model field as an argument.

一部のデータベースカラムの型は `CHAR(25)` などのパラメータを受け付けます。ここで、パラメータ `25` はカラムの最大長を表します。このような場合、パラメータを `db_type()` メソッド内でハードコードするよりも、モデル内で指定したほうがより柔軟になります。たとえば、ここで示すように、`CharMaxlength25Field` のようなフィールドを持つ意味はあまりありません。

```
# This is a silly example of hard-coded parameters.
class CharMaxlength25Field(models.Field):
    def db_type(self, connection):
        return "char(25)"

# In the model:
class MyModel(models.Model):
    # ...
    my_field = CharMaxlength25Field()
```

これを行うためのよりよい方法は、実行時に、つまりクラスがインスタンス化されるときにパラメータを指定できるようにする方法です。そのためには、次のように `Field.__init__()` を実装します。

```
# This is a much more flexible example.
class BetterCharField(models.Field):
    def __init__(self, max_length, *args, **kwargs):
        self.max_length = max_length
        super().__init__(*args, **kwargs)

    def db_type(self, connection):
        return "char(%s)" % self.max_length

# In the model:
class MyModel(models.Model):
    # ...
    my_field = BetterCharField(25)
```

最後に、カラムが本当に複雑な SQL のセットアップを必要とする場合、[`db_type()`](/ja/4.2/ref/models/fields/#django.db.models.Field.db_type) から `None` を返してください。こうすると、Django の SQL 生成コードがこのフィールドをスキップするようになります。その後、別の方法で正しいテーブルにカラムを作成すする必要がありますが、Django に邪魔をしないように伝えることができます。

[`rel_db_type()`](/ja/4.2/ref/models/fields/#django.db.models.Field.rel_db_type) メソッドは、他のフィールドを指す `ForeignKey` や `OneToOneField` などのフィールドによって、データベースのカラムのデータ型を特定するために呼ばれます。たとえば、`UnsignedAutoField` がある場合、同じデータ型を使うためにそのフィールドを指す外部キーも必要になります。

```
# MySQL unsigned integer (range 0 to 4294967295).
class UnsignedAutoField(models.AutoField):
    def db_type(self, connection):
        return "integer UNSIGNED AUTO_INCREMENT"

    def rel_db_type(self, connection):
        return "integer UNSIGNED"
```

#### 変数を Python オブジェクトに変換する

If your custom [`Field`](/ja/4.2/ref/models/fields/#django.db.models.Field) class deals with data structures that are more
complex than strings, dates, integers, or floats, then you may need to override
[`from_db_value()`](/ja/4.2/ref/models/fields/#django.db.models.Field.from_db_value) and [`to_python()`](/ja/4.2/ref/models/fields/#django.db.models.Field.to_python).

If present for the field subclass, `from_db_value()` will be called in all
circumstances when the data is loaded from the database, including in
aggregates and [`values()`](/ja/4.2/ref/models/querysets/#django.db.models.query.QuerySet.values) calls.

`to_python()` is called by deserialization and during the
[`clean()`](/ja/4.2/ref/models/instances/#django.db.models.Model.clean) method used from forms.

As a general rule, `to_python()` should deal gracefully with any of the
following arguments:

- An instance of the correct type (e.g., `Hand` in our ongoing example).
- 文字列
- `None` (フィールドが `null=True` を許す場合)

In our `HandField` class, we're storing the data as a `VARCHAR` field in
the database, so we need to be able to process strings and `None` in the
`from_db_value()`. In `to_python()`, we need to also handle `Hand`
instances:

```
import re

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

def parse_hand(hand_string):
    """Takes a string of cards and splits into a full hand."""
    p1 = re.compile(".{26}")
    p2 = re.compile("..")
    args = [p2.findall(x) for x in p1.findall(hand_string)]
    if len(args) != 4:
        raise ValidationError(_("Invalid input for a Hand instance"))
    return Hand(*args)

class HandField(models.Field):
    # ...

    def from_db_value(self, value, expression, connection):
        if value is None:
            return value
        return parse_hand(value)

    def to_python(self, value):
        if isinstance(value, Hand):
            return value

        if value is None:
            return value

        return parse_hand(value)
```

Notice that we always return a `Hand` instance from these methods. That's the
Python object type we want to store in the model's attribute.

For `to_python()`, if anything goes wrong during value conversion, you should
raise a [`ValidationError`](/ja/4.2/ref/exceptions/#django.core.exceptions.ValidationError) exception.

#### Python オブジェクトをクエリ変数に変換する

Since using a database requires conversion in both ways, if you override
[`from_db_value()`](/ja/4.2/ref/models/fields/#django.db.models.Field.from_db_value) you also have to override
[`get_prep_value()`](/ja/4.2/ref/models/fields/#django.db.models.Field.get_prep_value) to convert Python objects back to query values.

例えば:

```
class HandField(models.Field):
    # ...

    def get_prep_value(self, value):
        return "".join(
            ["".join(l) for l in (value.north, value.east, value.south, value.west)]
        )
```

> **Warning**
>
> If your custom field uses the `CHAR`, `VARCHAR` or `TEXT`
> types for MySQL, you must make sure that [`get_prep_value()`](/ja/4.2/ref/models/fields/#django.db.models.Field.get_prep_value)
> always returns a string type. MySQL performs flexible and unexpected
> matching when a query is performed on these types and the provided
> value is an integer, which can cause queries to include unexpected
> objects in their results. This problem cannot occur if you always
> return a string type from [`get_prep_value()`](/ja/4.2/ref/models/fields/#django.db.models.Field.get_prep_value).

#### クエリの変数をデータベースの変数に変換する

Some data types (for example, dates) need to be in a specific format
before they can be used by a database backend.
[`get_db_prep_value()`](/ja/4.2/ref/models/fields/#django.db.models.Field.get_db_prep_value) is the method where those conversions should
be made. The specific connection that will be used for the query is
passed as the `connection` parameter. This allows you to use
backend-specific conversion logic if it is required.

For example, Django uses the following method for its
[`BinaryField`](/ja/4.2/ref/models/fields/#django.db.models.BinaryField):

```
def get_db_prep_value(self, value, connection, prepared=False):
    value = super().get_db_prep_value(value, connection, prepared)
    if value is not None:
        return connection.Database.Binary(value)
    return value
```

In case your custom field needs a special conversion when being saved that is
not the same as the conversion used for normal query parameters, you can
override [`get_db_prep_save()`](/ja/4.2/ref/models/fields/#django.db.models.Field.get_db_prep_save).

#### 保存する前に前もって値を加工する場合

If you want to preprocess the value just before saving, you can use
[`pre_save()`](/ja/4.2/ref/models/fields/#django.db.models.Field.pre_save). For example, Django's
[`DateTimeField`](/ja/4.2/ref/models/fields/#django.db.models.DateTimeField) uses this method to set the attribute
correctly in the case of [`auto_now`](/ja/4.2/ref/models/fields/#django.db.models.DateField.auto_now) or
[`auto_now_add`](/ja/4.2/ref/models/fields/#django.db.models.DateField.auto_now_add).

もしこのメソッドをオーバーライドするならば、最後にその属性の値を返す必要があります。さらに、もしその値になんらかの変更を加えたならば、そのモデルへの参照を含んでいるコードが常に正しい値を指すように、モデルの属性を更新しなくてはなりません。

#### モデルフィールドのフォームフィールドの指定

To customize the form field used by [`ModelForm`](/ja/4.2/topics/forms/modelforms/#django.forms.ModelForm), you can
override [`formfield()`](/ja/4.2/ref/models/fields/#django.db.models.Field.formfield).

The form field class can be specified via the `form_class` and
`choices_form_class` arguments; the latter is used if the field has choices
specified, the former otherwise. If these arguments are not provided,
[`CharField`](/ja/4.2/ref/forms/fields/#django.forms.CharField) or [`TypedChoiceField`](/ja/4.2/ref/forms/fields/#django.forms.TypedChoiceField)
will be used.

All of the `kwargs` dictionary is passed directly to the form field's
`__init__()` method. Normally, all you need to do is set up a good default
for the `form_class` (and maybe `choices_form_class`) argument and then
delegate further handling to the parent class. This might require you to write
a custom form field (and even a form widget). See the [forms documentation](/ja/4.2/topics/forms/) for information about this.

Continuing our ongoing example, we can write the [`formfield()`](/ja/4.2/ref/models/fields/#django.db.models.Field.formfield) method
as:

```
class HandField(models.Field):
    # ...

    def formfield(self, **kwargs):
        # This is a fairly standard way to set up some defaults
        # while letting the caller override them.
        defaults = {"form_class": MyFormField}
        defaults.update(kwargs)
        return super().formfield(**defaults)
```

This assumes we've imported a `MyFormField` field class (which has its own
default widget). This document doesn't cover the details of writing custom form
fields.

#### 組み込みフィールド・タイプのエミュレート

If you have created a [`db_type()`](/ja/4.2/ref/models/fields/#django.db.models.Field.db_type) method, you don't need to worry about
[`get_internal_type()`](/ja/4.2/ref/models/fields/#django.db.models.Field.get_internal_type) -- it won't be used much. Sometimes, though, your
database storage is similar in type to some other field, so you can use that
other field's logic to create the right column.

例えば:

```
class HandField(models.Field):
    # ...

    def get_internal_type(self):
        return "CharField"
```

No matter which database backend we are using, this will mean that
[`migrate`](/ja/4.2/ref/django-admin/#django-admin-migrate) and other SQL commands create the right column type for
storing a string.

If [`get_internal_type()`](/ja/4.2/ref/models/fields/#django.db.models.Field.get_internal_type) returns a string that is not known to Django for
the database backend you are using -- that is, it doesn't appear in
`django.db.backends.<db_name>.base.DatabaseWrapper.data_types` -- the string
will still be used by the serializer, but the default [`db_type()`](/ja/4.2/ref/models/fields/#django.db.models.Field.db_type)
method will return `None`. See the documentation of [`db_type()`](/ja/4.2/ref/models/fields/#django.db.models.Field.db_type)
for reasons why this might be useful. Putting a descriptive string in as the
type of the field for the serializer is a useful idea if you're ever going to
be using the serializer output in some other place, outside of Django.

#### シリアライズするためにフィールドデータを変換する場合

To customize how the values are serialized by a serializer, you can override
[`value_to_string()`](/ja/4.2/ref/models/fields/#django.db.models.Field.value_to_string). Using [`value_from_object()`](/ja/4.2/ref/models/fields/#django.db.models.Field.value_from_object) is the
best way to get the field's value prior to serialization. For example, since
`HandField` uses strings for its data storage anyway, we can reuse some
existing conversion code:

```
class HandField(models.Field):
    # ...

    def value_to_string(self, obj):
        value = self.value_from_object(obj)
        return self.get_prep_value(value)
```

### 一般的なアドバイス

Writing a custom field can be a tricky process, particularly if you're doing
complex conversions between your Python types and your database and
serialization formats. Here are a couple of tips to make things go more
smoothly:

1. Look at the existing Django fields (in
   [django/db/models/fields/\_\_init\_\_.py](https://github.com/django/django/blob/stable/4.2.x/django/db/models/fields/__init__.py)) for inspiration. Try to find
   a field that's similar to what you want and extend it a little bit,
   instead of creating an entirely new field from scratch.
2. Put a `__str__()` method on the class you're wrapping up as a field. There
   are a lot of places where the default behavior of the field code is to call
   `str()` on the value. (In our examples in this document, `value` would
   be a `Hand` instance, not a `HandField`). So if your `__str__()`
   method automatically converts to the string form of your Python object, you
   can save yourself a lot of work.

## `FileField` サブクラスを書く

In addition to the above methods, fields that deal with files have a few other
special requirements which must be taken into account. The majority of the
mechanics provided by `FileField`, such as controlling database storage and
retrieval, can remain unchanged, leaving subclasses to deal with the challenge
of supporting a particular type of file.

Django provides a `File` class, which is used as a proxy to the file's
contents and operations. This can be subclassed to customize how the file is
accessed, and what methods are available. It lives at
`django.db.models.fields.files`, and its default behavior is explained in the
[file documentation](/ja/4.2/ref/files/file/).

Once a subclass of `File` is created, the new `FileField` subclass must be
told to use it. To do so, assign the new `File` subclass to the special
`attr_class` attribute of the `FileField` subclass.

### いくつかの提案

上記の詳細に加えて、フィールドのコードの効率と読みやすさを劇的に改善するいくつかのガイドラインがあります。

1. The source for Django's own `ImageField` (in
   [django/db/models/fields/files.py](https://github.com/django/django/blob/stable/4.2.x/django/db/models/fields/files.py)) is a great example of how to
   subclass `FileField` to support a particular type of file, as it
   incorporates all of the techniques described above.
2. Cache file attributes wherever possible. Since files may be stored in
   remote storage systems, retrieving them may cost extra time, or even
   money, that isn't always necessary. Once a file is retrieved to obtain
   some data about its content, cache as much of that data as possible to
   reduce the number of times the file must be retrieved on subsequent
   calls for that information.
