Python:sqlalchemy报错DetachedInstanceError

2024-01-07 20:30:29

sqlalchemy 对象commit之后再使用就会报错

DetachedInstanceError

既然这样,提交后还需要使用,就拷贝一个副本出来

一个思路是

# -*- coding: utf-8 -*-
"""
@File    : sqlalchemy_util.py
@Date    : 2024-01-07
@Author  : Peng Shiyu
"""
from datetime import datetime

from sqlalchemy.orm import class_mapper

from utils import time_util


def 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 item


def 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

文章来源:https://blog.csdn.net/mouday/article/details/135443353
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。