model_dump와 별칭을 활용한 직렬화
model_dump, 필드 별칭, 계산 필드, 직렬화 옵션을 사용해 Pydantic 모델을 데이터로 변환하거나 데이터에서 변환하는 방식을 제어하고 깔끔한 API 페이로드를 만듭니다.
model_dump와 별칭을 활용한 직렬화은(는) CoddyKit의 무료 FastAPI Backend Development Bootcamp 강의입니다. 이것은 4개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 FastAPI Backend Development Bootcamp 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. FastAPI Backend Development Bootcamp 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Serialization vs Validation
Pydantic does two jobs: validation (untrusted input becomes a typed model) and serialization (a model becomes a dict or JSON to send out). This lesson focuses on controlling the output side precisely.
model_dump Basics
In Pydantic v2, model_dump() turns a model into a dict and model_dump_json() into a JSON string.
from pydantic import BaseModel
class User(BaseModel):
name: str
age: int
u = User(name='Ada', age=36)
print(u.model_dump())
print(u.model_dump_json())Including and Excluding Fields
Trim the output with include or exclude to hide internal or sensitive fields from a payload.
u.model_dump(exclude={'age'})
u.model_dump(include={'name'})Dropping Defaults and None
Use exclude_none=True or exclude_defaults=True to produce leaner payloads that omit empty values.
class Profile(BaseModel):
name: str
bio: str | None = None
Profile(name='Ada').model_dump(exclude_none=True)Field Aliases
External APIs often use names like userName while Python prefers user_name. An alias maps between them.
from pydantic import BaseModel, Field
class User(BaseModel):
user_name: str = Field(alias='userName')Serializing by Alias
By default model_dump uses the Python field names. Pass by_alias=True to output the alias names instead.
u = User(userName='ada')
print(u.model_dump())
print(u.model_dump(by_alias=True))populate_by_name
Set model_config = ConfigDict(populate_by_name=True) to accept either the field name or the alias when parsing input, giving you flexibility on both ends.
from pydantic import ConfigDict
class User(BaseModel):
model_config = ConfigDict(populate_by_name=True)
user_name: str = Field(alias='userName')Computed Fields
Expose derived values in the output with @computed_field. They appear in model_dump but are not part of the input.
from pydantic import computed_field
class Person(BaseModel):
first: str
last: str
@computed_field
@property
def full(self) -> str:
return self.first + ' ' + self.lastCustom Field Serializers
Use @field_serializer to control how a specific field is rendered, for example formatting a datetime or masking a secret.
from pydantic import field_serializer
class Account(BaseModel):
card: str
@field_serializer('card')
def mask(self, v: str) -> str:
return '****' + v[-4:]Alias Mapping in Plain Python
The by_alias transform is just key renaming. Here is the concept without Pydantic.
data = {'user_name': 'ada', 'user_age': 36}
alias = {'user_name': 'userName', 'user_age': 'userAge'}
out = {alias[k]: v for k, v in data.items()}
print(out)FastAPI Response Integration
FastAPI serializes return values through your response_model. Set response_model_by_alias and exclusion flags on the route to shape the JSON your API emits.
@app.get('/user', response_model=User, response_model_by_alias=True)
async def get_user():
return User(user_name='ada')Quick Check
Your model has user_name: str = Field(alias='userName'). What does model_dump(by_alias=True) produce for the key?
Recap
You mastered Pydantic serialization:
model_dump/model_dump_jsonwith include, exclude, and exclude_none.- Aliases plus
by_aliasandpopulate_by_name. - Computed fields and custom field serializers.
- Wiring it into FastAPI response models.
자주 묻는 질문
“model_dump와 별칭을 활용한 직렬화” 강의는 무료인가요?
네 — “model_dump와 별칭을 활용한 직렬화” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 FastAPI Backend Development Bootcamp 강의 전체를 잠금 해제할 수 있습니다. FastAPI Backend Development Bootcamp 강의에는 총 4개의 강의가 포함되어 있습니다.
“model_dump와 별칭을 활용한 직렬화”에서 뭘 배우나요?
model_dump, 필드 별칭, 계산 필드, 직렬화 옵션을 사용해 Pydantic 모델을 데이터로 변환하거나 데이터에서 변환하는 방식을 제어하고 깔끔한 API 페이로드를 만듭니다. 브라우저에서 직접 실행하는 실습 코드로 FastAPI Backend Development Bootcamp을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
FastAPI Backend Development Bootcamp을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 FastAPI Backend Development Bootcamp은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 4번째 강의입니다.
“model_dump와 별칭을 활용한 직렬화” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 FastAPI Backend Development Bootcamp 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 FastAPI Backend Development Bootcamp 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- Pydantic 필드 검증 및 검증기
- 사용자 지정 데이터 형식 및 설정
- 중첩 모델 및 재귀 구조
- model_dump와 별칭을 활용한 직렬화