dimanche 12 juin 2016

Deleted rows from reflected table with SQLAlchemy


I have a table that I'm trying to delete data from. I have been using a Session() object to query data, and it works just fine. But when I go to delete a list of data, it fails.

# load engine and reflect.
engine = create_engine("...")
metadata = MetaData()
Session = sessionmaker(autoflush=True, autocommit=True)
Session.configure(bind=engine)
session = Session()
metadata.reflect(bind=engine)

# queries work.
table = Table("some_table", metadata, autoload_with=engine)
session.query(table).filter(table.c.column.between(dobj1,dobj2)).all()

# deletes do not.
session.query(table).filter(table.c.column.in_([1,2,3,4,5])).delete()

When I try to delete a bunch of rows, I get this:

File "/virtualenv/lib/python2.7/site-packages/sqlalchemy/orm/persistence.py", line 1180, in _do_pre_synchronize
    target_cls = query._mapper_zero().class_
AttributeError: 'Table' object has no attribute 'class_'

I tried this question's method, but it gives me this error:

File "/virtualenv/lib/python2.7/site-packages/sqlalchemy/sql/base.py", line 385, in execute
    raise exc.UnboundExecutionError(msg)
sqlalchemy.exc.UnboundExecutionError: This None is not directly bound to a Connection or Engine.Use the .execute() method of a Connection or Engine to execute this construct.

I tried to map it to a declarative base with automap_base(), but I just got different errors.

How can I delete rows from the table I loaded in the session I already have established?


Aucun commentaire:

Enregistrer un commentaire