model_dumpとエイリアスによるシリアライズ
model_dump、フィールドエイリアス、計算フィールド、シリアライズオプションを使い、Pydanticモデルをデータへ変換する方法、またデータから戻す方法を制御して、扱いやすいAPIペイロードを作成します。
「model_dumpとエイリアスによるシリアライズ」はCoddyKit上の無料FastAPI Backend Development Bootcampレッスンです。 これはレッスン4/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応の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時間対応のAIチューター)、FastAPI Backend Development Bootcampコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 FastAPI Backend Development Bootcampコースには全4レッスンが含まれています。
「model_dumpとエイリアスによるシリアライズ」で何を学びますか?
model_dump、フィールドエイリアス、計算フィールド、シリアライズオプションを使い、Pydanticモデルをデータへ変換する方法、またデータから戻す方法を制御して、扱いやすいAPIペイロードを作成します。 ブラウザで直接実行するハンズオンコードでFastAPI Backend Development Bootcampを演習し、24時間対応の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とエイリアスによるシリアライズ