python config_error ai_generated true

pydantic_core._pydantic_core.ValidationError: 1 validation error for User userName Field required [type=missing, input_value={'user_name': 'a'}, input_type=dict]

ID: python/pydantic-alias-population

Also available as: JSON · Markdown · 中文
80%Fix Rate
88%Confidence
0Evidence
2024-03-30First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
2.x active

Root Cause

Field declared with alias='userName' but input dict uses the Python name 'user_name'. populate_by_name was not enabled.

generic

中文

字段声明了 alias='userName',但输入字典使用 Python 名 'user_name'。未启用 populate_by_name。

Workarounds

  1. 95% success
    from pydantic import BaseModel, Field, ConfigDict
    class User(BaseModel):
        model_config = ConfigDict(populate_by_name=True)
        user_name: str = Field(alias='userName')
  2. 90% success
    from pydantic import BaseModel, Field, AliasChoices
    class User(BaseModel):
        user_name: str = Field(validation_alias=AliasChoices('userName', 'user_name'))

Dead Ends

Common approaches that don't work:

  1. 50% fail

    Violates PEP 8 and breaks all Python call sites using user_name.

  2. 65% fail

    Pydantic raises a name conflict error at class definition time.

  3. 55% fail

    Every caller must know the alias; error-prone and hides schema drift.