|
12 | 12 | InstrumentedAttribute, |
13 | 13 | MapperProperty, |
14 | 14 | RelationshipProperty, |
| 15 | + class_mapper, |
15 | 16 | joinedload, |
16 | 17 | lazyload, |
17 | 18 | selectinload, |
@@ -88,22 +89,98 @@ def get_instrumented_attr( |
88 | 89 | return key |
89 | 90 |
|
90 | 91 |
|
| 92 | +def _convert_relationship_value( |
| 93 | + value: Any, |
| 94 | + related_model: type[ModelT], |
| 95 | + is_collection: bool, |
| 96 | +) -> Any: |
| 97 | + """Convert a relationship value, handling dicts, lists, and instances. |
| 98 | +
|
| 99 | + Args: |
| 100 | + value: The value to convert (dict, list, model instance, or None). |
| 101 | + related_model: The SQLAlchemy model class for the relationship. |
| 102 | + is_collection: Whether this is a collection relationship (uselist=True). |
| 103 | +
|
| 104 | + Returns: |
| 105 | + Converted value appropriate for the relationship type. |
| 106 | + """ |
| 107 | + if value is None: |
| 108 | + return None |
| 109 | + |
| 110 | + if is_collection: |
| 111 | + # One-to-many or many-to-many: expect a list |
| 112 | + if not isinstance(value, (list, tuple)): |
| 113 | + # Single item provided for collection - wrap in list |
| 114 | + value = [value] |
| 115 | + return [ |
| 116 | + model_from_dict(related_model, **item) if isinstance(item, dict) else item |
| 117 | + for item in value # pyright: ignore[reportUnknownVariableType] |
| 118 | + ] |
| 119 | + # One-to-one or many-to-one: expect single value |
| 120 | + if isinstance(value, dict): |
| 121 | + return model_from_dict(related_model, **value) |
| 122 | + return value |
| 123 | + |
| 124 | + |
91 | 125 | def model_from_dict(model: type[ModelT], **kwargs: Any) -> ModelT: |
92 | 126 | """Create an ORM model instance from a dictionary of attributes. |
93 | 127 |
|
| 128 | + This function recursively converts nested dictionaries into their |
| 129 | + corresponding SQLAlchemy model instances for relationship attributes. |
| 130 | +
|
94 | 131 | Args: |
95 | 132 | model: The SQLAlchemy model class to instantiate. |
96 | 133 | **kwargs: Keyword arguments containing model attribute values. |
| 134 | + For relationship attributes, values can be: |
| 135 | + - None: Sets the relationship to None |
| 136 | + - dict: Recursively converted to the related model instance |
| 137 | + - list[dict]: Each dict converted to related model instances |
| 138 | + - Model instance: Passed through unchanged |
97 | 139 |
|
98 | 140 | Returns: |
99 | 141 | ModelT: A new instance of the model populated with the provided values. |
| 142 | +
|
| 143 | + Example: |
| 144 | + Basic usage with nested relationships:: |
| 145 | +
|
| 146 | + data = { |
| 147 | + "name": "John Doe", |
| 148 | + "profile": {"bio": "Developer"}, |
| 149 | + "addresses": [ |
| 150 | + {"street": "123 Main St"}, |
| 151 | + {"street": "456 Oak Ave"}, |
| 152 | + ], |
| 153 | + } |
| 154 | + user = model_from_dict(User, **data) |
| 155 | + # user.profile is a Profile instance |
| 156 | + # user.addresses is a list of Address instances |
100 | 157 | """ |
101 | | - data = { |
102 | | - attr_name: kwargs[attr_name] |
103 | | - for attr_name in model.__mapper__.attrs.keys() # noqa: SIM118 # pyright: ignore[reportUnknownMemberType] |
104 | | - if attr_name in kwargs |
105 | | - } |
106 | | - return model(**data) |
| 158 | + mapper = class_mapper(model) |
| 159 | + mapper_attrs = mapper.attrs |
| 160 | + converted_data: dict[str, Any] = {} |
| 161 | + |
| 162 | + # Iterate over kwargs instead of mapper.attrs for better performance |
| 163 | + # when only a subset of attributes is provided (O(InputKeys) vs O(TotalColumns)) |
| 164 | + for key, value in kwargs.items(): |
| 165 | + # Skip keys that aren't mapped attributes (e.g., extra fields) |
| 166 | + if key not in mapper_attrs: |
| 167 | + continue |
| 168 | + |
| 169 | + attr = mapper_attrs[key] |
| 170 | + |
| 171 | + # Check if this attribute is a relationship |
| 172 | + if isinstance(attr, RelationshipProperty): |
| 173 | + related_model: type[ModelT] = attr.mapper.class_ |
| 174 | + converted_data[key] = _convert_relationship_value( |
| 175 | + value=value, |
| 176 | + related_model=related_model, |
| 177 | + is_collection=attr.uselist or False, |
| 178 | + ) |
| 179 | + else: |
| 180 | + # Regular column attribute - pass through |
| 181 | + converted_data[key] = value |
| 182 | + |
| 183 | + return model(**converted_data) |
107 | 184 |
|
108 | 185 |
|
109 | 186 | def get_abstract_loader_options( |
|
0 commit comments