フィールド
??? API「APIドキュメント」 [pydantic.fields.Field
.フィールド ][pydantic.fields.フィールド]
Field
関数は、モデルのフィールドをカスタマイズしてメタデータを追加するために使用されます。
デフォルト値¶
default
パラメータは、フィールドのデフォルト値を定義するために使用されます。
from pydantic import BaseModel, Field
class User(BaseModel):
name: str = Field(default='John Doe')
user = User()
print(user)
#> name='John Doe'
また、 default_factory
使用して、デフォルト値を生成するために呼び出される呼び出し可能オブジェクトを定義することもできます。
from uuid import uuid4
from pydantic import BaseModel, Field
class User(BaseModel):
id: str = Field(default_factory=lambda: uuid4().hex)
!!! default
とdefault_factory
パラメータは相互に排他的です。
!!!注: typing.Optional
を使用する場合、フィールドのデフォルト値がNone
になるわけではありません。
Annotated
の使用¶
Field
関数はAnnotated
と併用することもできます。
from uuid import uuid4
from typing_extensions import Annotated
from pydantic import BaseModel, Field
class User(BaseModel):
id: Annotated[str, Field(default_factory=lambda: uuid4().hex)]
!!! note デフォルトは、 Annotated
外側で割り当てられた値として設定することも、 Annotated
内のField.default_factory
を使用して設定することもできます。 Field.default
引数はAnnotated
内ではサポートされません。
フィールドのエイリアス¶
検証とシリアル化のために、フィールドのエイリアスを定義できます。
エイリアスを定義するには 3 つの方法があります。
Field(..., alias='foo')
Field(..., validation_alias='foo')
Field(..., serialization_alias='foo')
alias
パラメーターは、検証_と_シリアル化の両方に使用されます。検証とシリアル化にそれぞれ_異なる_エイリアスを使用する場合は、 validation_alias
パラメーターとserialization_alias
パラメーターを使用できます。これらのパラメーターは、それぞれの使用例にのみ適用されます。
以下は、 alias
パラメータの使用例です。
from pydantic import BaseModel, Field
class User(BaseModel):
name: str = Field(..., alias='username')
user = User(username='johndoe') # (1)!
print(user)
#> name='johndoe'
print(user.model_dump(by_alias=True)) # (2)!
#> {'username': 'johndoe'}
- エイリアス
'username'
は、インスタンスの作成と検証に使用されます。 model_dump
使用してモデルをシリアル化可能な形式に変換しています。
model_dump
の詳細については、API リファレンスを参照してください。
by_alias
キーワード引数のデフォルトはFalse
であり、フィールド (シリアル化) エイリアスを使用してモデルをダンプするには明示的に指定する必要があることに注意してください。
by_alias=True
の場合、シリアル化中にエイリアス'username'
も使用されます。
検証_のみ_にエイリアスを使用したい場合は、 validation_alias
パラメーターを使用できます。
from pydantic import BaseModel, Field
class User(BaseModel):
name: str = Field(..., validation_alias='username')
user = User(username='johndoe') # (1)!
print(user)
#> name='johndoe'
print(user.model_dump(by_alias=True)) # (2)!
#> {'name': 'johndoe'}
- 検証エイリアス
'username'
は検証中に使用されます。 - フィールド名
'name'
はシリアル化中に使用されます。
_シリアライゼーション_のエイリアスを定義したいだけの場合は、 serialization_alias
パラメータを使用できます。
from pydantic import BaseModel, Field
class User(BaseModel):
name: str = Field(..., serialization_alias='username')
user = User(name='johndoe') # (1)!
print(user)
#> name='johndoe'
print(user.model_dump(by_alias=True)) # (2)!
#> {'username': 'johndoe'}
- フィールド名
'name'
は検証に使用されます。 - シリアル化には、シリアル化エイリアス
'username'
が使用されます。
!!! note 「エイリアスの優先順位と優先順位」 alias
validation_alias
またはserialization_alias
と同時に使用する場合、検証ではvalidation_alias
alias
よりも優先され、 serialization_alias
シリアル化ではalias
よりも優先されます。
If you use an `alias_generator` in the [Model Config][pydantic.config.ConfigDict.alias_generator], you can control
the order of precedence for specified field vs generated aliases via the `alias_priority` setting. You can read more about alias precedence [here](../concepts/alias.md#alias-precedence).
???ヒント「VSCode および Pyright ユーザー」 VSCode では、 Pylance拡張機能を使用すると、フィールドのエイリアスを使用してモデルをインスタンス化するときに警告が表示されません。
```py
from pydantic import BaseModel, Field
class User(BaseModel):
name: str = Field(..., alias='username')
user = User(username='johndoe') # (1)!
```
1. VSCode will NOT show a warning here.
When the `'alias'` keyword argument is specified, even if you set `populate_by_name` to `True` in the
[Model Config][pydantic.config.ConfigDict.populate_by_name], VSCode will show a warning when instantiating
a model using the field name (though it will work at runtime) — in this case, `'name'`:
```py
from pydantic import BaseModel, ConfigDict, Field
class User(BaseModel):
model_config = ConfigDict(populate_by_name=True)
name: str = Field(..., alias='username')
user = User(name='johndoe') # (1)!
```
1. VSCode will show a warning here.
To "trick" VSCode into preferring the field name, you can use the `str` function to wrap the alias value.
With this approach, though, a warning is shown when instantiating a model using the alias for the field:
```py
from pydantic import BaseModel, ConfigDict, Field
class User(BaseModel):
model_config = ConfigDict(populate_by_name=True)
name: str = Field(..., alias=str('username')) # noqa: UP018
user = User(name='johndoe') # (1)!
user = User(username='johndoe') # (2)!
```
1. Now VSCode will NOT show a warning
2. VSCode will show a warning here, though
This is discussed in more detail in [this issue](https://github.com/pydantic/pydantic/issues/5893).
### Validation Alias
Even though Pydantic treats `alias` and `validation_alias` the same when creating model instances, VSCode will not
use the `validation_alias` in the class initializer signature. If you want VSCode to use the `validation_alias`
in the class initializer, you can instead specify both an `alias` and `serialization_alias`, as the
`serialization_alias` will override the `alias` during serialization:
```py
from pydantic import BaseModel, Field
class MyModel(BaseModel):
my_field: int = Field(..., validation_alias='myValidationAlias')
```
with:
```py
from pydantic import BaseModel, Field
class MyModel(BaseModel):
my_field: int = Field(
...,
alias='myValidationAlias',
serialization_alias='my_serialization_alias',
)
m = MyModel(myValidationAlias=1)
print(m.model_dump(by_alias=True))
#> {'my_serialization_alias': 1}
```
All of the above will likely also apply to other tools that respect the
[`@typing.dataclass_transform`](https://docs.python.org/3/library/typing.html#typing.dataclass_transform)
decorator, such as Pyright.
エイリアスの使用方法の詳細については、「エイリアスの概念」ページを参照してください。
数値制約¶
数値を制限するために使用できるキーワード引数がいくつかあります。
gt
- より大きいlt
- より小さいge
- 以上le
- 以下multiple_of
- 指定された数値の倍数allow_inf_nan
-'inf'
、'-inf'
、'nan'
値を許可します
以下に例を示します。
from pydantic import BaseModel, Field
class Foo(BaseModel):
positive: int = Field(gt=0)
non_negative: int = Field(ge=0)
negative: int = Field(lt=0)
non_positive: int = Field(le=0)
even: int = Field(multiple_of=2)
love_for_pydantic: float = Field(allow_inf_nan=True)
foo = Foo(
positive=1,
non_negative=0,
negative=-1,
non_positive=0,
even=2,
love_for_pydantic=float('inf'),
)
print(foo)
"""
positive=1 non_negative=0 negative=-1 non_positive=0 even=2 love_for_pydantic=inf
"""
??? info "JSON Schema" 生成された JSON スキーマ:
- `gt` and `lt` constraints will be translated to `exclusiveMinimum` and `exclusiveMaximum`.
- `ge` and `le` constraints will be translated to `minimum` and `maximum`.
- `multiple_of` constraint will be translated to `multipleOf`.
The above snippet will generate the following JSON Schema:
```json
{
"title": "Foo",
"type": "object",
"properties": {
"positive": {
"title": "Positive",
"type": "integer",
"exclusiveMinimum": 0
},
"non_negative": {
"title": "Non Negative",
"type": "integer",
"minimum": 0
},
"negative": {
"title": "Negative",
"type": "integer",
"exclusiveMaximum": 0
},
"non_positive": {
"title": "Non Positive",
"type": "integer",
"maximum": 0
},
"even": {
"title": "Even",
"type": "integer",
"multipleOf": 2
},
"love_for_pydantic": {
"title": "Love For Pydantic",
"type": "number"
}
},
"required": [
"positive",
"non_negative",
"negative",
"non_positive",
"even",
"love_for_pydantic"
]
}
```
See the [JSON Schema Draft 2020-12] for more details.
!!!警告「複合型の制約」 複合型でフィールド制約を使用すると、場合によってはエラーが発生する可能性があります。潜在的な問題を回避するには、 Annotated
を使用できます。
```py
from typing import Optional
from typing_extensions import Annotated
from pydantic import BaseModel, Field
class Foo(BaseModel):
positive: Optional[Annotated[int, Field(gt=0)]]
# Can error in some cases, not recommended:
non_negative: Optional[int] = Field(ge=0)
```
文字列制約¶
??? API「APIドキュメント」 pydantic.types.StringConstraints
文字列を制限するために使用できるフィールドがあります。
min_length
: 文字列の最小長。max_length
: 文字列の最大長。pattern
: 文字列が一致する必要がある正規表現。
以下に例を示します。
from pydantic import BaseModel, Field
class Foo(BaseModel):
short: str = Field(min_length=3)
long: str = Field(max_length=10)
regex: str = Field(pattern=r'^\d*$') # (1)!
foo = Foo(short='foo', long='foobarbaz', regex='123')
print(foo)
#> short='foo' long='foobarbaz' regex='123'
```
1. Only digits are allowed.
??? info "JSON Schema"
In the generated JSON schema:
- `min_length` constraint will be translated to `minLength`.
- `max_length` constraint will be translated to `maxLength`.
- `pattern` constraint will be translated to `pattern`.
The above snippet will generate the following JSON Schema:
```json
{
"title": "Foo",
"type": "object",
"properties": {
"short": {
"title": "Short",
"type": "string",
"minLength": 3
},
"long": {
"title": "Long",
"type": "string",
"maxLength": 10
},
"regex": {
"title": "Regex",
"type": "string",
"pattern": "^\\d*$"
}
},
"required": [
"short",
"long",
"regex"
]
}
```
## Decimal Constraints
There are fields that can be used to constrain decimals:
* `max_digits`: Maximum number of digits within the `Decimal`. It does not include a zero before the decimal point or
trailing decimal zeroes.
* `decimal_places`: Maximum number of decimal places allowed. It does not include trailing decimal zeroes.
Here's an example:
```py
from decimal import Decimal
from pydantic import BaseModel, Field
class Foo(BaseModel):
precise: Decimal = Field(max_digits=5, decimal_places=2)
foo = Foo(precise=Decimal('123.45'))
print(foo)
#> precise=Decimal('123.45')
データクラスの制約¶
データクラスを制約するために使用できるフィールドがあります。
init
: フィールドをデータクラスの__init__
に含めるかどうか。init_var
: フィールドをデータクラスの初期化専用フィールドとして見なすべきかどうか。kw_only
: フィールドをデータクラスのコンストラクターのキーワードのみの引数にするかどうか。
以下に例を示します。
from pydantic import BaseModel, Field
from pydantic.dataclasses import dataclass
@dataclass
class Foo:
bar: str
baz: str = Field(init_var=True)
qux: str = Field(kw_only=True)
class Model(BaseModel):
foo: Foo
model = Model(foo=Foo('bar', baz='baz', qux='qux'))
print(model.model_dump()) # (1)!
#> {'foo': {'bar': 'bar', 'qux': 'qux'}}
baz
フィールドは init 専用フィールドであるため、model_dump()
出力には含まれません。
デフォルト値の検証¶
パラメータvalidate_default
使用して、フィールドのデフォルト値を検証するかどうかを制御できます。
デフォルトでは、フィールドのデフォルト値は検証されません。
from pydantic import BaseModel, Field, ValidationError
class User(BaseModel):
age: int = Field(default='twelve', validate_default=True)
try:
user = User()
except ValidationError as e:
print(e)
"""
1 validation error for User
age
Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='twelve', input_type=str]
"""
フィールド表現¶
パラメーターrepr
使用して、フィールドをモデルの文字列表現に含めるかどうかを制御できます。
from pydantic import BaseModel, Field
class User(BaseModel):
name: str = Field(repr=True) # (1)!
age: int = Field(repr=False)
user = User(name='John', age=42)
print(user)
#> name='John'
- これがデフォルト値です。
ディスクリミネーター¶
パラメーターdiscriminator
使用して、結合内の異なるモデルを区別するために使用されるフィールドを制御できます。フィールドの名前またはDiscriminator
インスタンスのいずれかを受け取ります。 Discriminator
アプローチは、 Union
内のすべてのモデルで Discriminator フィールドが同じではない場合に役立ちます。
次の例は、フィールド名でdiscriminator
使用する方法を示しています。
from typing import Literal, Union
from pydantic import BaseModel, Field
class Cat(BaseModel):
pet_type: Literal['cat']
age: int
class Dog(BaseModel):
pet_type: Literal['dog']
age: int
class Model(BaseModel):
pet: Union[Cat, Dog] = Field(discriminator='pet_type')
print(Model.model_validate({'pet': {'pet_type': 'cat', 'age': 12}})) # (1)!
#> pet=Cat(pet_type='cat', age=12)
次の例は、 Discriminator
インスタンスでdiscriminator
キーワード引数を使用する方法を示しています。
from typing import Literal, Union
from typing_extensions import Annotated
from pydantic import BaseModel, Discriminator, Field, Tag
class Cat(BaseModel):
pet_type: Literal['cat']
age: int
class Dog(BaseModel):
pet_kind: Literal['dog']
age: int
def pet_discriminator(v):
if isinstance(v, dict):
return v.get('pet_type', v.get('pet_kind'))
return getattr(v, 'pet_type', getattr(v, 'pet_kind', None))
class Model(BaseModel):
pet: Union[Annotated[Cat, Tag('cat')], Annotated[Dog, Tag('dog')]] = Field(
discriminator=Discriminator(pet_discriminator)
)
print(repr(Model.model_validate({'pet': {'pet_type': 'cat', 'age': 12}})))
#> Model(pet=Cat(pet_type='cat', age=12))
print(repr(Model.model_validate({'pet': {'pet_kind': 'dog', 'age': 12}})))
#> Model(pet=Dog(pet_kind='dog', age=12))
Annotated
を利用して、判別共用体を定義することもできます。詳細については、 Discriinated Union のドキュメントを参照してください。
ストリクトモード¶
Field
のstrict
パラメーターは、フィールドを「strict モード」で検証するかどうかを指定します。 strict モードでは、Pydantic は、 strict=True
のフィールドにデータを強制する代わりに、検証中にエラーをスローします。
from pydantic import BaseModel, Field
class User(BaseModel):
name: str = Field(strict=True) # (1)!
age: int = Field(strict=False)
user = User(name='John', age='42') # (2)!
print(user)
#> name='John' age=42
- これがデフォルト値です。
age
フィールドは厳密モードでは検証されません。したがって、文字列を割り当てることができます。
詳細については、 「厳密モード」を参照してください。
Pydantic が strict モードと lax モードの両方でデータを変換する方法の詳細については、 「変換テーブル」を参照してください。
不変性¶
パラメータfrozen
凍結されたデータクラスの動作をエミュレートするために使用されます。これは、モデルの作成後にフィールドに新しい値が割り当てられないようにするために使用されます (不変性)。
詳細については、凍結されたデータクラスのドキュメントを参照してください。
from pydantic import BaseModel, Field, ValidationError
class User(BaseModel):
name: str = Field(frozen=True)
age: int
user = User(name='John', age=42)
try:
user.name = 'Jane' # (1)!
except ValidationError as e:
print(e)
"""
1 validation error for User
name
Field is frozen [type=frozen_field, input_value='Jane', input_type=str]
"""
name
フィールドが固定されているため、割り当ては許可されません。
除外する¶
exclude
パラメーターを使用して、モデルをエクスポートするときにモデルから除外するフィールドを制御できます。
次の例を参照してください。
from pydantic import BaseModel, Field
class User(BaseModel):
name: str
age: int = Field(exclude=True)
user = User(name='John', age=42)
print(user.model_dump()) # (1)!
#> {'name': 'John'}
age
フィールドは除外されているため、model_dump()
出力には含まれません。
詳細については、 「シリアル化」セクションを参照してください。
非推奨のフィールド¶
deprecated
パラメーターを使用して、フィールドを非推奨としてマークすることができます。そうすると、次のような結果が得られます。
- フィールドにアクセスするときに発行される実行時非推奨警告。
"deprecated": true
が設定されています。
非deprecated
パラメータは次のいずれかとして設定できます。
- 非推奨メッセージとして使用される文字列。
warnings.deprecated
デコレーター (またはtyping_extensions
バックポート) のインスタンス。- ブール値。デフォルトの
'deprecated'
メッセージでフィールドを非推奨としてマークするために使用されます。
文字列としてはdeprecated
¶
from typing_extensions import Annotated
from pydantic import BaseModel, Field
class Model(BaseModel):
deprecated_field: Annotated[int, Field(deprecated='This is deprecated')]
print(Model.model_json_schema()['properties']['deprecated_field'])
#> {'deprecated': True, 'title': 'Deprecated Field', 'type': 'integer'}
warnings.deprecated
デコレータによってdeprecated
¶
!!! note 注 非deprecated
デコレータをこの方法で使用できるのは、 typing_extensions
>= 4.9.0 がインストールされている場合のみです。
import importlib.metadata
from packaging.version import Version
from typing_extensions import Annotated, deprecated
from pydantic import BaseModel, Field
if Version(importlib.metadata.version('typing_extensions')) >= Version('4.9'):
class Model(BaseModel):
deprecated_field: Annotated[int, deprecated('This is deprecated')]
# Or explicitly using `Field`:
alt_form: Annotated[
int, Field(deprecated=deprecated('This is deprecated'))
]
ブール値としてdeprecated
¶
from typing_extensions import Annotated
from pydantic import BaseModel, Field
class Model(BaseModel):
deprecated_field: Annotated[int, Field(deprecated=True)]
print(Model.model_json_schema()['properties']['deprecated_field'])
#> {'deprecated': True, 'title': 'Deprecated Field', 'type': 'integer'}
!!! note " category
とstacklevel
のサポート" この機能の現在の実装では、 deprecated
デコレータに対するcategory
とstacklevel
引数が考慮されていません。これは Pydantic の将来のバージョンに組み込まれる可能性があります。
!!!警告「バリデーターの非推奨フィールドへのアクセス」 バリデーター内の非推奨フィールドにアクセスすると、非推奨の警告が表示されます。 catch_warnings
を使用すると、これを明示的に無視できます。
```py
import warnings
from typing_extensions import Self
from pydantic import BaseModel, Field, model_validator
class Model(BaseModel):
deprecated_field: int = Field(deprecated='This is deprecated')
@model_validator(mode='after')
def validate_model(self) -> Self:
with warnings.catch_warnings():
warnings.simplefilter('ignore', DeprecationWarning)
self.deprecated_field = self.deprecated_field * 2
```
JSON スキーマのカスタマイズ¶
一部のフィールド パラメーターは、生成された JSON スキーマをカスタマイズするためにのみ使用されます。問題のパラメータは次のとおりです。
title
description
examples
json_schema_extra
JSON スキーマのカスタマイズ/フィールドを使用した変更の詳細については、JSON スキーマ ドキュメントの「JSON スキーマのカスタマイズ」セクションを参照してください。
computed_field
デコレータ¶
??? API「APIドキュメント」 pydantic.fields.computed_field
モデルまたはデータクラスをシリアル化するときに、 computed_field
デコレーターを使用してproperty
またはcached_property
属性を含めることができます。これは、他のフィールドから計算されるフィールドや、計算にコストがかかる (したがってキャッシュされる) フィールドに便利です。
以下に例を示します。
from pydantic import BaseModel, computed_field
class Box(BaseModel):
width: float
height: float
depth: float
@computed_field
def volume(self) -> float:
return self.width * self.height * self.depth
b = Box(width=1, height=2, depth=3)
print(b.model_dump())
#> {'width': 1.0, 'height': 2.0, 'depth': 3.0, 'volume': 6.0}
通常のフィールドと同様に、計算フィールドも非推奨としてマークできます。
from typing_extensions import deprecated
from pydantic import BaseModel, computed_field
class Box(BaseModel):
width: float
height: float
depth: float
@computed_field
@deprecated("'volume' is deprecated")
def volume(self) -> float:
return self.width * self.height * self.depth
本文总阅读量次