无法使用 SQLAlchemy 从数据库中删除实例

Can't remove an instance from data base using SQLAlchemy

我无法使用 SQLAlchemy 从数据库中删除实例。

这是代码:

from sqlalchemy.orm import sessionmaker, scoped_session
from zope.sqlalchemy import ZopeTransactionExtension
from sqlalchemy import create_engine
from sqlalchemy import MetaData
from sqlalchemy.ext.declarative import declarative_base
from pyspatialite import dbapi2 as sqlite
import transaction

maker = sessionmaker(autoflush=True, autocommit=False, extension=ZopeTransactionExtension())
DBSession = scoped_session(maker)
metadata = MetaData()
Base = declarative_base(metadata=metadata)

filename="/net/my_db.db"
dburi = 'sqlite:///{0}'.format(filename)
engine = create_engine(dburi, module=sqlite, echo=False, encoding="utf8")
metadata.bind = engine
DBSession.configure(bind=engine)

my_table = metadata.tables['table_name']
name_col = my_table.columns['col_name']
my_instance = DBSession.query(my_table).filter(name_col == "toto").first()

DBSession.delete(my_instance)

然后我有以下错误:

UnmappedInstanceError: Class 'sqlalchemy.util._collections.KeyedTuple' is not mapped

我找到了有效的答案:

my_table = metadata.tables['table_name']
name_col = my_table.columns['col_name']
id_col = my_table.columns['id']
old_id, = DBSession.query(id_col).filter(name_col == "toto").first()
my_instance = DBSession.query(ClassMap).get(old_id)

DBSession.delete(my_instance)

transaction.commit()