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
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
populate_by_name for pydantic 2.x within the model_confighate_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...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.