我想借助sqlalchemy将数据从一个数据库传输到另一个数据库。问题是,如何确定id为none,以便目标数据库而不是源数据库将对象识别为新对象。
粗略的例子: T恤类源DB中的对象: {id = 1,颜色=“红色”} 现在,当我尝试将对象复制到目标数据库时,我认为将ID手动设置为 none 就足够了。
以下是相关代码:
def transfer_from_db1_to_db2(db_config_section_1, db_config_section_2):
cloths = db_op.db_get_all_entrys_of(db_config_section_1, Cloth)
cloths_no_id = []
for cloth in cloths:
cloth.id = None;
cloths_no_id.append(cloth)
db_op.db_save(cloths_no_id, db_config_section_2)
def db_get_all_entrys_of(db_config_section:str, class_type):
session = create_session(db_config_section)
objects = session.query(class_type).all()
session.close()
return objects
def db_save(objects:[], db_config_section:str):
session = create_session(db_config_section)
for obj in objects:
session.add(obj)
session.flush()
session.commit()
session.close()
此处显示错误消息(已缩短):
Traceback (most recent call last):
...
File "C:\Users\user1\Anaconda3\lib\site-packages\sqlalchemy\orm\persistence.py", line 797, in _emit_update_statements
(table.description, len(records), rows))
sqlalchemy.orm.exc.StaleDataError: UPDATE statement on table 'cloth' expected to update 159757 row(s); 0 were matched.
感谢可能的遮阳篷和帮助。