การทำให้เป็นอนุกรมด้วย model_dump และนามแฝง
ควบคุมวิธีแปลงโมเดล Pydantic ไปเป็นข้อมูลและแปลงกลับด้วย model_dump นามแฝงของฟิลด์ ฟิลด์ที่คำนวณได้ และตัวเลือกการทำให้เป็นอนุกรม เพื่อสร้างข้อมูลส่งให้ API ที่สะอาด
การทำให้เป็นอนุกรมด้วย model_dump และนามแฝง เป็นบทเรียน FastAPI Backend Development Bootcamp ฟรีบน CoddyKit นี่คือบทเรียนที่ 4 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน 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 และนามแฝง” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส FastAPI Backend Development Bootcamp ให้อัปเกรดเป็น CoddyKit PRO คอร์ส FastAPI Backend Development Bootcamp มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การทำให้เป็นอนุกรมด้วย model_dump และนามแฝง”
ควบคุมวิธีแปลงโมเดล Pydantic ไปเป็นข้อมูลและแปลงกลับด้วย model_dump นามแฝงของฟิลด์ ฟิลด์ที่คำนวณได้ และตัวเลือกการทำให้เป็นอนุกรม เพื่อสร้างข้อมูลส่งให้ API ที่สะอาด คุณปฏิบัติ FastAPI Backend Development Bootcamp ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน FastAPI Backend Development Bootcamp หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน FastAPI Backend Development Bootcamp บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 4 จากทั้งหมด 4 บทเรียน
บทเรียน “การทำให้เป็นอนุกรมด้วย model_dump และนามแฝง” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน FastAPI Backend Development Bootcamp นี้ได้ไหม
ได้ บทเรียน FastAPI Backend Development Bootcamp ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- การตรวจสอบฟิลด์และตัวตรวจสอบของ Pydantic
- ชนิดข้อมูลและการตั้งค่าแบบกำหนดเอง
- โมเดลซ้อนกันและโครงสร้างเวียนเกิด
- การทำให้เป็นอนุกรมด้วย model_dump และนามแฝง