0Pricing
FastAPI Backend Development Bootcamp · บทเรียน

โมเดลซ้อนกันและโครงสร้างเวียนเกิด

จัดการโครงสร้าง JSON ที่ซ้อนกันหลายระดับและโมเดลข้อมูลเวียนเกิดอย่างมีประสิทธิภาพด้วย Pydantic

โมเดลซ้อนกันและโครงสร้างเวียนเกิด เป็นบทเรียน FastAPI Backend Development Bootcamp ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน FastAPI Backend Development Bootcamp และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส FastAPI Backend Development Bootcamp มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Understanding Nested Pydantic Models

In real-world applications, data is rarely flat. It often has a hierarchical structure, meaning some data points are collections of other data points.

Nested models in Pydantic allow you to define complex data structures by embedding one BaseModel within another. This helps you build robust and well-organized data schemas.

Defining Your First Nested Model

Let's create an Address model and then use it as a field within a User model. Notice how address: Address links the two.

from pydantic import BaseModel

class Address(BaseModel):
    street: str
    city: str
    zip_code: str

class User(BaseModel):
    name: str
    email: str
    address: Address

# We'll see it in action next!

Instantiating Nested Pydantic Models

Now, let's create an instance of our User model. Pydantic automatically validates the nested Address data, ensuring all required fields are present and correctly typed.

from pydantic import BaseModel

class Address(BaseModel):
    street: str
    city: str
    zip_code: str

class User(BaseModel):
    name: str
    email: str
    address: Address

if __name__ == "__main__":
    user_data = {
        "name": "Alice Wonderland",
        "email": "alice@example.com",
        "address": {
            "street": "123 Rabbit Hole",
            "city": "Wonderland",
            "zip_code": "90210"
        }
    }
    user = User(**user_data)
    print(f"User: {user.name}")
    print(f"Lives in: {user.address.city}")

    # Pydantic will validate nested data:
    try:
        User(name="Bob", email="b@example.com", address={"street": "Main"})
    except Exception as e:
        print(f"\nValidation Error (expected): {e}")

Lists of Nested Pydantic Models

You can also have fields that are lists of other Pydantic models. This is common for things like a user having multiple items, or a product having several features.

We use List from the typing module for this.

from typing import List
from pydantic import BaseModel

class Skill(BaseModel):
    name: str
    level: int # e.g., 1-5

class Developer(BaseModel):
    name: str
    skills: List[Skill]

if __name__ == "__main__":
    dev_data = {
        "name": "Grace Hopper",
        "skills": [
            {"name": "Python", "level": 5},
            {"name": "SQL", "level": 4},
            {"name": "Algorithms", "level": 3}
        ]
    }
    developer = Developer(**dev_data)
    print(f"Developer: {developer.name}")
    print("Skills:")
    for skill in developer.skills:
        print(f"- {skill.name} (Level: {skill.level})")

Unlocking Recursive Pydantic Models

Sometimes, data structures are even more complex: they refer to themselves. This is called a recursive model.

  • Think of a comment section where replies are also comments.
  • An organizational chart where employees can have managers who are also employees.
  • A file system where folders contain other folders.

Pydantic can handle these self-referencing structures elegantly.

The Challenge of Self-Referencing Types

When a model needs to refer to itself, Python faces a "chicken-and-egg" problem: how can you define a type that isn't fully defined yet?

Pydantic solves this using forward references. In Pydantic v2 (and often in v1 with string literals), you can simply use the model's name as a string for the type hint.

Modeling an Org Chart with Recursion

Let's create an Employee model where an employee can have a manager (who is also an Employee) and a list of subordinates (also Employees).

Notice the use of 'Employee' as a string for the type hint to enable the recursion.

from typing import List, Optional
from pydantic import BaseModel

class Employee(BaseModel):
    name: str
    title: str
    # 'Employee' is a forward reference to itself
    manager: Optional['Employee'] = None
    subordinates: List['Employee'] = []

# We'll build an org chart in the next scene!

Building a Recursive Data Structure

Here's how you can instantiate the Employee model to build a small organizational hierarchy. Pydantic handles the validation of each nested/recursive layer.

from typing import List, Optional
from pydantic import BaseModel

class Employee(BaseModel):
    name: str
    title: str
    manager: Optional['Employee'] = None
    subordinates: List['Employee'] = []

if __name__ == "__main__":
    # Create employees
    ceo = Employee(name="Mr. Boss", title="CEO")
    manager_a = Employee(name="Ms. Lead", title="Manager A", manager=ceo)
    dev_1 = Employee(name="Dev One", title="Developer", manager=manager_a)
    dev_2 = Employee(name="Dev Two", title="Developer", manager=manager_a)

    # Link subordinates (Pydantic can also do this from structured data dicts)
    manager_a.subordinates.extend([dev_1, dev_2])
    ceo.subordinates.append(manager_a)

    print(f"Org Chart: {ceo.name} ({ceo.title})")
    for sub in ceo.subordinates:
        print(f"  - {sub.name} ({sub.title})")
        for dev in sub.subordinates:
            print(f"    - {dev.name} ({dev.title})")

    # You can also parse a dictionary directly:
    org_data = {
        "name": "Top CEO", "title": "CEO",
        "subordinates": [
            {
                "name": "Mid Manager", "title": "Manager",
                "subordinates": [
                    {"name": "Junior Dev", "title": "Developer"}
                ]
            }
        ]
    }
    full_org = Employee(**org_data)
    print(f"\nParsed Org: {full_org.name} -> {full_org.subordinates[0].name} -> {full_org.subordinates[0].subordinates[0].name}")

Validation in Recursive Models

Just like with nested models, Pydantic's validation engine works seamlessly with recursive structures. It ensures that every level of the hierarchy conforms to the defined model, catching type errors or missing fields.

This makes handling complex, self-referencing data much safer and easier to manage.

Nested & Recursive Model Check

Let's check your understanding of Pydantic's powerful data modeling features.

Recap: Mastering Complex Data Structures

You've learned how to handle complex data with Pydantic!

  • Nested models allow you to compose complex data structures from simpler ones, with automatic validation at every level.
  • Recursive models enable you to define self-referencing data, perfect for hierarchies like organizational charts or comment threads.
  • Pydantic's use of forward references (often string literals) makes defining recursive types straightforward.

These techniques are fundamental for building robust and clear APIs that interact with structured data.

คำถามที่พบบ่อย

บทเรียน “โมเดลซ้อนกันและโครงสร้างเวียนเกิด” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “โมเดลซ้อนกันและโครงสร้างเวียนเกิด” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส FastAPI Backend Development Bootcamp ให้อัปเกรดเป็น CoddyKit PRO คอร์ส FastAPI Backend Development Bootcamp มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “โมเดลซ้อนกันและโครงสร้างเวียนเกิด”

จัดการโครงสร้าง JSON ที่ซ้อนกันหลายระดับและโมเดลข้อมูลเวียนเกิดอย่างมีประสิทธิภาพด้วย Pydantic คุณปฏิบัติ FastAPI Backend Development Bootcamp ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน FastAPI Backend Development Bootcamp หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน FastAPI Backend Development Bootcamp บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน

บทเรียน “โมเดลซ้อนกันและโครงสร้างเวียนเกิด” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน FastAPI Backend Development Bootcamp นี้ได้ไหม

ได้ บทเรียน FastAPI Backend Development Bootcamp ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. การตรวจสอบฟิลด์และตัวตรวจสอบของ Pydantic
  2. ชนิดข้อมูลและการตั้งค่าแบบกำหนดเอง
  3. โมเดลซ้อนกันและโครงสร้างเวียนเกิด
  4. การทำให้เป็นอนุกรมด้วย model_dump และนามแฝง
← กลับไปที่ FastAPI Backend Development Bootcamp