콘텐츠로 이동

필드

??? api "API 문서" pydantic.fields.Field

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)

!!! info defaultdefault_factory 매개변수는 상호 배타적입니다.

!!! note 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 내에서 지원되지 않습니다.

필드 별칭

유효성 검사 및 직렬화를 위해 필드에 대한 별칭을 정의할 수 있습니다.

별칭을 정의하는 방법에는 세 가지가 있습니다.

  • Field(..., alias='foo')
  • Field(..., validation_alias='foo')
  • Field(..., serialization_alias='foo')

alias 매개 변수는 유효성 검사 직렬화에 모두 사용됩니다. 유효성 검사와 직렬화에 각각 다른 별칭을 사용하려는 경우 해당 사용 사례에만 적용되는 validation_aliasserialization_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'}
  1. 별칭 'username' 인스턴스 생성 및 유효성 검사에 사용됩니다.
  2. 우리는 model_dump 사용하여 모델을 직렬화 가능한 형식으로 변환합니다.

API 참조에서 model_dump에 대한 자세한 내용을 볼 수 있습니다.

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'}
  1. 유효성 검사 중에는 유효성 검사 별칭 'username' 사용됩니다.
  2. 필드 이름 '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'}
  1. 필드 이름 'name' 이 유효성 검사에 사용됩니다.
  2. 직렬화 별칭 '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).

??? Tip "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.

!!! warning "복합 유형에 대한 제약 조건" 복합 유형에 필드 제약 조건을 사용하는 경우 경우에 따라 오류가 발생할 수 있습니다. 잠재적인 문제를 방지하려면 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'}}
  1. 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'
  1. 이것이 기본값입니다.

판별자

매개변수 discriminator 공용체에서 서로 다른 모델을 구별하는 데 사용되는 필드를 제어하는 데 사용할 수 있습니다. 필드 이름이나 Discriminator 인스턴스 중 하나를 사용합니다. Discriminator 접근 방식은 판별자 필드가 Union 의 모든 모델에 대해 동일하지 않을 때 유용할 수 있습니다.

다음 예에서는 필드 이름과 함께 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)
  1. 모델 페이지에서 도우미 기능 에 대해 자세히 알아보세요.

다음 예에서는 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 를 활용하여 구별된 공용체를 정의할 수도 있습니다. 자세한 내용은 Discriminate Unions 문서를 참조하세요.

엄격 모드

Fieldstrict 매개변수는 필드가 "엄격 모드"에서 유효성을 검사해야 하는지 여부를 지정합니다. 엄격 모드에서 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
  1. 이것이 기본값입니다.
  2. 엄격 모드에서는 age 필드의 유효성이 검사되지 않습니다. 따라서 문자열을 할당할 수 있습니다.

자세한 내용은 엄격 모드를 참조하세요.

Pydantic이 엄격 모드와 완화 모드 모두에서 데이터를 변환하는 방법에 대한 자세한 내용은 변환 표를 참조하세요.

불변성

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]
    """
  1. 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'}
  1. 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 typing_extensions >= 4.9.0이 설치된 경우에만 이 방식으로 더 이상 사용 deprecated 데코레이터를 사용할 수 있습니다.

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 " categorystacklevel 지원" 이 기능의 현재 구현에서는 deprecated 데코레이터에 대한 categorystacklevel 인수를 고려하지 않습니다. 이는 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

本文总阅读量