0Pricing
FastAPI Backend Development Bootcamp · 课时

使用 model_dump 与别名进行序列化

使用 model_dump、字段别名、计算字段和序列化选项,控制 Pydantic 模型如何与数据相互转换,从而生成整洁的 API 负载。

使用 model_dump 与别名进行序列化 是 CoddyKit 上的免费 FastAPI Backend Development Bootcamp 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 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.last

Custom 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_json with include, exclude, and exclude_none.
  • Aliases plus by_alias and populate_by_name.
  • Computed fields and custom field serializers.
  • Wiring it into FastAPI response models.

常见问题解答

「使用 model_dump 与别名进行序列化」课时是免费的吗?

是的 — 「使用 model_dump 与别名进行序列化」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 FastAPI Backend Development Bootcamp 课程的其余内容,请升级到 CoddyKit PRO。 FastAPI Backend Development Bootcamp 课程共包含 4 节课。

「使用 model_dump 与别名进行序列化」这节课中我会学到什么?

使用 model_dump、字段别名、计算字段和序列化选项,控制 Pydantic 模型如何与数据相互转换,从而生成整洁的 API 负载。 你通过在浏览器中直接运行的动手代码来练习 FastAPI Backend Development Bootcamp,全天候 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 反馈 — 无需本地设置。

此课程中的所有课时

  1. Pydantic 字段验证与验证器
  2. 自定义数据类型与设置
  3. 嵌套模型与递归结构
  4. 使用 model_dump 与别名进行序列化
← 返回 FastAPI Backend Development Bootcamp