This rule raises an issue when both validate_by_alias and validate_by_name are explicitly set to False in a
Pydantic v2 ConfigDict.
Data modeling frameworks use configuration options to determine how field values can be provided during object instantiation: one option controls whether fields can be populated using alternative names (aliases), and another controls whether they can be populated using their declared attribute names. These options control the valid input methods for providing data to the model’s fields.
When both options are disabled, the model has no way to accept input data. This creates an invalid configuration that will cause errors when describing the model, as there is no valid method to pass values to any field.
According to the framework documentation:
You cannot set both validation options to disable alias-based and name-based population. This would make it impossible to populate an attribute.
This misconfiguration typically occurs when developers are trying to restrict how data is provided to the model, but inadvertently disable all input methods.
In Pydantic specifically, these configuration options are validate_by_alias and validate_by_name in the model’s
ConfigDict or Config class.
When both validation options are disabled, a PydanticUserError is raised at class definition time. This prevents the application from
starting up correctly and requires the developer to fix the configuration before the model can be used.
Enable validate_by_name to allow field population using attribute names. This is the most straightforward solution and allows fields
to be populated using their Python attribute names.
from pydantic import BaseModel, ConfigDict, Field
class Model(BaseModel):
model_config = ConfigDict(
validate_by_alias=False,
validate_by_name=False # Noncompliant
)
my_field: str = Field(alias='my_alias')
from pydantic import BaseModel, ConfigDict, Field
class Model(BaseModel):
model_config = ConfigDict(
validate_by_alias=False,
validate_by_name=True
)
my_field: str = Field(alias='my_alias')