sqlalchemy 对象commit之后再使用就会报错
DetachedInstanceError
既然这样,提交后还需要使用,就拷贝一个副本出来
一个思路是
# -*- coding: utf-8 -*-
"""
@File : sqlalchemy_util.py
@Date : 2024-01-07
@Author : Peng Shiyu
"""
from datetime import datetimefrom sqlalchemy.orm import class_mapperfrom utils import time_utildef to_json(model):columns = [column.key for column in class_mapper(model.__class__).columns]item = {}for column in columns:item[column] = getattr(model, column)return itemdef copy(source, target=None):"""属性浅拷贝:param source: object:param target: Model / dict:return:"""if not target:if isinstance(source, dict):return {**source}else:target = source.__class__()# BaseModel 使用 SQLAlchemy 定义if isinstance(target, BaseModel):for column in class_mapper(source.__class__).columns:if hasattr(source, column.key):setattr(target, column.key, getattr(source, column.key))elif isinstance(target, dict):for key in target.keys():if hasattr(source, key):target[key] = getattr(source, key)return target