Skip to content

Leverage Pydantic's from_attributes for cleaner SQLAlchemy-to-Model mapping #367

@nanotaboada

Description

@nanotaboada
Owner

Description

The current code manually maps SQLAlchemy ORM instances to Pydantic models using .model_dump() and dict unpacking. This creates redundant boilerplate and tight coupling between data structures.

Pydantic v2 introduces from_attributes=True (formerly from_orm=True), enabling Pydantic models to load data directly from SQLAlchemy models via attribute access — reducing manual overhead and improving maintainability.

Proposed Solution

Leverage model_validate(instance) with from_attributes=True to automatically generate Pydantic models from SQLAlchemy models.

Suggested Implementation

  1. Add model_config = ConfigDict(from_attributes=True) to the relevant Pydantic models (e.g.: PlayerModel).
  2. Replace manual conversions like PlayerModel(**player.__dict__)with PlayerModel.model_validate(player)

Acceptance Criteria

  • All Pydantic models involved in ORM serialization use from_attributes=True.
  • Manual dictionary unpacking (**obj.__dict__) is removed in favor of model_validate().
  • Unit and integration tests pass without regressions.
  • Behavior remains consistent when serializing responses or performing validation.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

enhancementNew feature or requestpythonPull requests that update Python code

Projects

No projects

Milestone

No milestone

Relationships

None yet

    Development

    No branches or pull requests

      Participants

      @nanotaboada

      Issue actions

        Leverage Pydantic's `from_attributes` for cleaner SQLAlchemy-to-Model mapping · Issue #367 · nanotaboada/python-samples-fastapi-restful