Search code examples
python-2.7sqlalchemyzope

Can't remove an instance from data base using SQLAlchemy


I can't remove an instance from data base using SQLAlchemy.

Here is the code :

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)

Then I have the following error :

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


Solution

  • I found an answer that works :

    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()