Skip to content

Conversation

ravishan16
Copy link

Description

This PR fixes the Field(alias="...") functionality that was broken in Pydantic v2 while maintaining full backward compatibility with Pydantic v1.

Problem

In Pydantic v2, the alias parameter in SQLModel's Field function was not working correctly for validation and serialization. The issue was that Pydantic v2 requires explicit validation_alias and serialization_alias parameters, but SQLModel wasn't automatically propagating the alias value to these parameters.

Solution

Changes Made:

  1. Enhanced Field function:

    • Added validation_alias and serialization_alias parameters
    • Implemented version-specific parameter handling
  2. Automatic alias propagation:

    • Modified post_init_field_info in _compat.py to automatically set validation_alias and serialization_alias from alias when not explicitly provided (Pydantic v2 only)
  3. Backward compatibility:

    • Filter out v2-only parameters from FieldInfo in Pydantic v1
    • Raise clear RuntimeError when v2 features are used with v1
    • Conditional test execution based on Pydantic version
  4. Comprehensive testing:

    • Added extensive test coverage for both Pydantic v1 and v2
    • Tests automatically skip v2-specific features when running with v1
    • Covers all alias scenarios including edge cases

Breaking Changes
None. This is purely a bug fix with backward compatibility maintained.

Closes
Fixes #1536

@ravishan16 ravishan16 marked this pull request as ready for review September 25, 2025 23:02
@svlandeg svlandeg added the bug Something isn't working label Sep 26, 2025
@svlandeg svlandeg self-assigned this Sep 26, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Field(alias="") doesn't work with Pydantic V2
2 participants