1919)
2020
2121from pydantic import VERSION as P_VERSION
22- from pydantic import BaseModel
22+ from pydantic import BaseModel , ConfigDict
2323from pydantic .fields import FieldInfo
2424from 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