From af62f7659c9af8b632fbffabf4a5b790f1be534c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=B0=A2=E7=BF=8A=E5=87=A1?= Date: Wed, 26 Aug 2026 15:45:49 +0800 Subject: [PATCH] fix: guard by_name kwarg for pydantic < 2.11 Co-Authored-By: Claude --- polyfactory/factories/pydantic_factory.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/polyfactory/factories/pydantic_factory.py b/polyfactory/factories/pydantic_factory.py index 7a1e5ca5..05b013e2 100644 --- a/polyfactory/factories/pydantic_factory.py +++ b/polyfactory/factories/pydantic_factory.py @@ -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 @@ -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)