Skip to content

Commit 170b343

Browse files
committed
feat: enhance handling of association proxies in SQLModel initialization
1 parent c875330 commit 170b343

File tree

1 file changed

+26
-1
lines changed

1 file changed

+26
-1
lines changed

sqlmodel/_compat.py

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
)
2020

2121
from pydantic import VERSION as P_VERSION
22-
from pydantic import BaseModel
22+
from pydantic import BaseModel, ConfigDict
2323
from pydantic.fields import FieldInfo
2424
from typing_extensions import Annotated, get_args, get_origin
2525

@@ -350,6 +350,15 @@ def sqlmodel_validate(
350350
value = getattr(use_obj, key, Undefined)
351351
if value is not Undefined:
352352
setattr(new_obj, key, value)
353+
# Get and set any association proxy objects
354+
for key in new_obj.__sqlalchemy_association_proxies__:
355+
# Handle both dict and object access
356+
if isinstance(use_obj, dict):
357+
value = use_obj.get(key, Undefined)
358+
else:
359+
value = getattr(use_obj, key, Undefined)
360+
if value is not Undefined:
361+
setattr(new_obj, key, value)
353362
return new_obj
354363

355364
def sqlmodel_init(*, self: "SQLModel", data: Dict[str, Any]) -> None:
@@ -556,6 +565,20 @@ def sqlmodel_validate(
556565
setattr(m, key, value)
557566
# Continue with standard Pydantic logic
558567
object.__setattr__(m, "__fields_set__", fields_set)
568+
# Handle non-Pydantic fields like relationships and association proxies
569+
if getattr(cls.__config__, "table", False): # noqa
570+
non_pydantic_keys = set(obj.keys()) - set(values.keys())
571+
for key in non_pydantic_keys:
572+
if (
573+
hasattr(m, "__sqlmodel_relationships__")
574+
and key in m.__sqlmodel_relationships__
575+
):
576+
setattr(m, key, obj[key])
577+
elif (
578+
hasattr(m, "__sqlalchemy_association_proxies__")
579+
and key in m.__sqlalchemy_association_proxies__
580+
):
581+
setattr(m, key, obj[key])
559582
m._init_private_attributes() # type: ignore[attr-defined] # noqa
560583
return m
561584

@@ -578,3 +601,5 @@ def sqlmodel_init(*, self: "SQLModel", data: Dict[str, Any]) -> None:
578601
for key in non_pydantic_keys:
579602
if key in self.__sqlmodel_relationships__:
580603
setattr(self, key, data[key])
604+
elif key in self.__sqlalchemy_association_proxies__:
605+
setattr(self, key, data[key])

0 commit comments

Comments
 (0)