MCPcopy Index your code
hub / github.com/fastapi/sqlmodel / sqlmodel_validate

Function sqlmodel_validate

sqlmodel/_compat.py:276–326  ·  view source on GitHub ↗
(
    cls: type[_TSQLModel],
    obj: Any,
    *,
    strict: bool | None = None,
    from_attributes: bool | None = None,
    context: dict[str, Any] | None = None,
    update: dict[str, Any] | None = None,
)

Source from the content-addressed store, hash-verified

274
275
276def sqlmodel_validate(
277 cls: type[_TSQLModel],
278 obj: Any,
279 *,
280 strict: bool | None = None,
281 from_attributes: bool | None = None,
282 context: dict[str, Any] | None = None,
283 update: dict[str, Any] | None = None,
284) -> _TSQLModel:
285 if not is_table_model_class(cls):
286 new_obj: _TSQLModel = cls.__new__(cls)
287 else:
288 # If table, create the new instance normally to make SQLAlchemy create
289 # the _sa_instance_state attribute
290 # The wrapper of this function should use with _partial_init()
291 with partial_init():
292 new_obj = cls()
293 # SQLModel Override to get class SQLAlchemy __dict__ attributes and
294 # set them back in after creating the object
295 old_dict = new_obj.__dict__.copy()
296 use_obj = obj
297 if isinstance(obj, dict) and update:
298 use_obj = {**obj, **update}
299 elif update:
300 use_obj = ObjectWithUpdateWrapper(obj=obj, update=update)
301 cls.__pydantic_validator__.validate_python(
302 use_obj,
303 strict=strict,
304 from_attributes=from_attributes,
305 context=context,
306 self_instance=new_obj,
307 )
308 # Capture fields set to restore it later
309 fields_set = new_obj.__pydantic_fields_set__.copy()
310 if not is_table_model_class(cls):
311 # If not table, normal Pydantic code, set __dict__
312 new_obj.__dict__ = {**old_dict, **new_obj.__dict__}
313 else:
314 # Do not set __dict__, instead use setattr to trigger SQLAlchemy
315 # instrumentation
316 for key, value in {**old_dict, **new_obj.__dict__}.items():
317 setattr(new_obj, key, value)
318 # Restore fields set
319 object.__setattr__(new_obj, "__pydantic_fields_set__", fields_set)
320 # Get and set any relationship objects
321 if is_table_model_class(cls):
322 for key in new_obj.__sqlmodel_relationships__:
323 value = getattr(use_obj, key, Undefined)
324 if value is not Undefined:
325 setattr(new_obj, key, value)
326 return new_obj
327
328
329def sqlmodel_init(*, self: "SQLModel", data: dict[str, Any]) -> None:

Callers 1

model_validateMethod · 0.85

Calls 5

is_table_model_classFunction · 0.85
partial_initFunction · 0.85
__new__Method · 0.45
__setattr__Method · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…