Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion polyfactory/factories/pydantic_factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,9 @@
from pydantic.v1.fields import DeferredType, ModelField, Undefined


_PYDANTIC_HAS_BY_NAME = tuple(map(int, VERSION.split(".")[:2])) >= (2, 11)


if TYPE_CHECKING:
from collections import abc
from collections.abc import Iterable, Mapping, Sequence
Expand Down Expand Up @@ -567,7 +570,9 @@ def _create_model(cls, _build_context: PydanticBuildContext, **kwargs: Any) -> T

# Use model_validate with by_name for Pydantic v2 models when requested
if cls.__by_name__ and _is_pydantic_v2_model(cls.__model__):
return cls.__model__.model_validate(kwargs, by_name=True) # type: ignore[return-value]
if _PYDANTIC_HAS_BY_NAME:
return cls.__model__.model_validate(kwargs, by_name=True) # type: ignore[return-value]
return cls.__model__.model_validate(kwargs) # type: ignore[return-value]

return cls.__model__(**kwargs)

Expand Down
Loading