한양과학기술고등학교

에듀테크 프로젝트 대시보드

Pydantic v2 모델

BaseModel Field model_config 중첩 모델 v2

Pydantic 은 FastAPI 의 데이터 계층입니다. 요청 검증, 응답 직렬화, 설정 관리가 모두 이 위에서 돌아갑니다.

1. 기본 모델

from datetime import datetime
from pydantic import BaseModel

class Article(BaseModel):
    id: int
    title: str
    body: str = ""                 # 기본값
    tags: list[str] = []
    created_at: datetime | None = None

Article(id=1, title="글")           # 나머지는 기본값
Article(id="1", title="글")         # "1" -> 1 자동 강제 변환(coercion)

2. Field — 제약과 메타데이터

from pydantic import BaseModel, Field

class User(BaseModel):
    name: str = Field(min_length=1, max_length=20)
    age: int = Field(ge=0, le=150)
    email: str = Field(pattern=r"^[^@]+@[^@]+$")
    bio: str = Field(default="", description="자기소개")
    role: str = Field(default="member", alias="userRole")

3. 중첩·리스트 모델

class Image(BaseModel):
    url: str
    alt: str = ""

class Product(BaseModel):
    name: str
    images: list[Image] = []
    primary: Image | None = None

# 들어온 dict 가 재귀적으로 Image 로 검증됨

4. model_config

from pydantic import BaseModel, ConfigDict

class Item(BaseModel):
    model_config = ConfigDict(
        from_attributes=True,   # ORM 객체 -> 모델 (v1 의 orm_mode)
        populate_by_name=True,  # alias 와 필드명 둘 다 허용
        str_strip_whitespace=True,
        extra="forbid",         # 정의 안 된 키가 오면 에러
    )
    name: str

5. 직렬화 / 역직렬화

item = Item.model_validate(raw_dict)      # dict -> 모델 (검증)
item = Item.model_validate_json(raw_str)  # JSON 문자열 -> 모델

item.model_dump()                        # -> dict
item.model_dump(mode="json")             # datetime 등도 JSON 호환 값으로
item.model_dump_json()                   # -> JSON 문자열
item.model_dump(exclude_none=True, exclude={"id"})

6. v1 → v2 이름 변화

Pydantic v1Pydantic v2
.dict().model_dump()
.json().model_dump_json()
.parse_obj().model_validate()
class Config:model_config = ConfigDict(...)
orm_mode = Truefrom_attributes=True
@validator@field_validator
@root_validator@model_validator
"마이그레이션 없는 스키마 변경은 사고의 시작이다"