45

How can I create a pydantic object, without useing alias names?

from pydantic import BaseModel, Field

class Params(BaseModel):
    var_name: int = Field(alias='var_alias')

Params(var_alias=5) # works
Params(var_name=5) # does not work

2 Answers 2

67

As of the pydantic 2.0 release, this behaviour has been updated to use model_config populate_by_name option which is False by default.

from pydantic import BaseModel, Field, ConfigDict


class Params(BaseModel):
    var_name: int = Field(alias='var_alias')

    model_config = ConfigDict(
        populate_by_name=True,
    )

Params(var_alias=5)  # works
Params(var_name=5)   # works

For pydantic 1.x, you need to use allow_population_by_field_name model config option.

from pydantic import BaseModel, Field


class Params(BaseModel):
    var_name: int = Field(alias='var_alias')

    class Config:
        allow_population_by_field_name = True


Params(var_alias=5)  # works
Params(var_name=5)   # works
Sign up to request clarification or add additional context in comments.

5 Comments

its a lifesaver! - might be because am a beginner in this!
This form of configuration has been deprecated.
Added edit - use populate_by_name for pydantic 2.x within the model_config
I've been looking for this answer for hours this morning and afternoon! I searched and searched the pydantic docs and maybe it's there but it is NOT prominent, that's for sure!!!!
Is there any way to do this when I don't have control of the model? For example, OpenAI assigns these wild alias' with "/" in them. hate_threatening: List[Literal["text"]] = FieldInfo(alias="hate/threatening") I'd love to be able to pass on option in when creating the object to ignore alias...
0

You can also continue using the pydantic v1 config definition in pydantic v2 by just changing the attribute name from allow_population_by_field_name to populate_by_name.

from pydantic import BaseModel, Field

class Params(BaseModel):
    var_name: int = Field(alias='var_alias')

    class Config:
        populate_by_name = True


Params(var_alias=5)    # OK
Params(var_name=5)     # OK

Yet another way is to simply set a dictionary as the default value to model_config parameter in the class definition. This works because ConfigDict is actually just a typing.TypedDict sub-class so if you know the set of acceptable keys, you can just pass a dict with no problem.

class Params(BaseModel):
    var_name: int = Field(alias='var_alias')
    model_config = {"populate_by_name": True}


Params(var_alias=5)    # OK
Params(var_name=5)     # OK

FYI, the link to the relevant documentation is here.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.