0Pricing
FastAPI Backend Development Bootcamp · درس

التسلسل باستخدام model_dump والأسماء المستعارة

تحكم في كيفية تحويل نماذج Pydantic إلى بيانات ومنها باستخدام model_dump والأسماء المستعارة للحقول والحقول المحسوبة وخيارات التسلسل لإنشاء حمولات API نظيفة.

التسلسل باستخدام model_dump والأسماء المستعارة درس مجاني في FastAPI Backend Development Bootcamp على CoddyKit. هذا هو الدرس 4 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 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.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 والأسماء المستعارة» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة FastAPI Backend Development Bootcamp، انتقل إلى CoddyKit PRO. تتضمن دورة FastAPI Backend Development Bootcamp 4 دروس في المجموع.

ماذا ستتعلم في «التسلسل باستخدام model_dump والأسماء المستعارة»؟

تحكم في كيفية تحويل نماذج Pydantic إلى بيانات ومنها باستخدام model_dump والأسماء المستعارة للحقول والحقول المحسوبة وخيارات التسلسل لإنشاء حمولات API نظيفة. تتمرن على FastAPI Backend Development Bootcamp مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 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 يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.

جميع الدروس في هذه الدورة

  1. التحقق من حقول Pydantic وأدوات التحقق
  2. أنواع البيانات المخصّصة والإعدادات
  3. النماذج المتداخلة والبنى التكرارية
  4. التسلسل باستخدام model_dump والأسماء المستعارة
← العودة إلى FastAPI Backend Development Bootcamp