[Python] How to define a Pydantic model that extracts nested attribute values from an ORM...

Discussão em 'Python' iniciado por Stack, Junho 17, 2025.

  1. Stack

    Stack Membro Participativo

    I'm using Pydantic v2 to define different response models depending on the use case. Some models reflect the structure of the ORM model exactly, and .model_validate(obj) works fine in those cases.

    However, I often need to "flatten" the data — instead of including a nested model, I want to extract a specific field from it and include it as a top-level field.

    Here's a simplified example:

    from dataclasses import dataclass
    from pydantic import BaseModel
    from pydantic.config import ConfigDict

    @dataclass # Let's pretend it's a SQLAlchemy model
    class Organization:
    name: str
    registration_number: str

    @dataclass # Let's pretend it's a SQLAlchemy model
    class Employee:
    name: str
    age: int
    organization: Organization

    class OrganizationResponse(BaseModel):
    model_config = ConfigDict(from_attributes=True)

    name: str
    registration_number: str

    class EmployeeDetailResponse(BaseModel):
    model_config = ConfigDict(from_attributes=True)

    name: str
    age: int
    organization: OrganizationResponse

    class EmployeeListItemResponse(BaseModel):
    model_config = ConfigDict(from_attributes=True)

    name: str
    age: int
    organization_name: str

    @classmethod
    def from_orm(cls, obj: Employee) -> "EmployeeListItemResponse":
    return cls(
    name=obj.name,
    age=obj.age,
    organization_name=obj.organization.name
    )


    Calling EmployeeDetailResponse.model_validate(employee_obj) works fine, as expected.

    But EmployeeListItemResponse.model_validate(employee_obj) fails, because organization_name doesn't directly exist in the employee_obj. So I had to write a custom .from_orm() for that.

    The issue is: I end up using .model_validate() in some models and custom .from_orm() in others. This inconsistency feels messy and harder to maintain.

    ❓ My question: How can I define models like EmployeeListItemResponse that include derived or nested attributes (e.g. employee.organization.name) and still use .model_validate(...)? Are there any existing tools or patterns in Pydantic that help with such transformations in a clean, reusable way?

    Continue reading...

Compartilhe esta Página