@@ -149,7 +149,7 @@ class Address:
149149 number: int
150150 zip_code: int
151151 city: str
152-
152+
153153class PersonInfo :
154154 def __init__ (self , name : str , age : int , address : Address):
155155 self .name = name
@@ -181,6 +181,42 @@ print("Target public_info.address is same as source address: ", address is publi
181181* [ TortoiseORM] ( https://github.com/tortoise/tortoise-orm )
182182* [ SQLAlchemy] ( https://www.sqlalchemy.org/ )
183183
184+ ## Complexer mapping registration
185+
186+ Support for defining mappings using ` lambda ` s.
187+
188+ ``` python
189+ class AgeGroup (Enum ):
190+ CHILD = " child"
191+ TEENAGER = " teenager"
192+ ADULT = " adult"
193+ SENIOR = " senior"
194+
195+ class UserInfo :
196+ def __init__ (self , name : str , profession : str , age : int ):
197+ self .name = name
198+ self .profession = profession
199+ self .age = age
200+
201+ class PublicUserInfo :
202+ def __init__ (self , name : str , profession : str , age_group : AgeGroup):
203+ self .name = name
204+ self .profession = profession
205+ self .age_group
206+
207+ mapper.add(UserInfo, PublicUserInfo, fields_mapping = {)
208+ " age_group" : lambda user : (
209+ AgeGroup.CHILD if user.age < 13 else
210+ AgeGroup.TEENAGER if user.age < 20 else
211+ AgeGroup.ADULT if user.age < 65 else
212+ AgeGroup.SENIOR
213+ )
214+ })
215+
216+ mapper.map(UserInfo(" John Malkovich" , " engineer" , 35 ))
217+ # {'name': 'John Malkovich', 'profession': 'engineer', 'age_group': <AgeGroup.ADULT: 'adult'>}
218+ ```
219+
184220## Pydantic/FastAPI Support
185221Out of the box Pydantic models support:
186222``` python
@@ -273,7 +309,7 @@ class PublicUserInfo(Base):
273309 id = Column(Integer, primary_key = True )
274310 public_name = Column(String)
275311 hobbies = Column(String)
276-
312+
277313obj = UserInfo(
278314 id = 2 ,
279315 full_name = " Danny DeVito" ,
@@ -304,7 +340,7 @@ class TargetClass:
304340 def __init__ (self , ** kwargs ):
305341 self .name = kwargs[" name" ]
306342 self .age = kwargs[" age" ]
307-
343+
308344 @ staticmethod
309345 def get_fields (cls ):
310346 return [" name" , " age" ]
@@ -358,7 +394,7 @@ T = TypeVar("T")
358394
359395def class_has_fields_property (target_cls : Type[T]) -> bool :
360396 return callable (getattr (target_cls, " fields" , None ))
361-
397+
362398mapper.add_spec(class_has_fields_property, lambda t : getattr (t, " fields" )())
363399
364400target_obj = mapper.to(TargetClass).map(source_obj)
0 commit comments