In the code below I set up two users using an orm session, and then
delete one of them with a second orm session.
----
import sqlalchemy as sa
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
Base = declarative_base()
class User(Base):
__tablename__ = "users"
id = sa.Column(sa.Integer, primary_key=True)
name = sa.Column(sa.String)
fullname = sa.Column(sa.String)
def __init__(self, name, fullname):
self.name = name
self.fullname = fullname
import os
dbEngine = sa.create_engine("sqlite://", echo = True)
Base.metadata.create_all(dbEngine)
Session = sessionmaker(bind = dbEngine,
autoflush = True,
autocommit = False)
#Add some data...
s1 = Session()
u1 = User("fred", "Fred Flintstone")
u2 = User("barney", "Barney Rubble")
s1.add(u1)
s1.add(u2)
s1.commit()
#delete the fred user...
name_to_delete = "fred"
s2 = Session()
fred = s2.query(User).filter_by(name = name_to_delete).first()
s2.delete(fred)
s2.commit()
----
In this reduced example I magically know the user name I want to
delete ("fred") and know that it exists. I also obviously don't need
the second session in this example, but it is a reduction of my
problem.
The SQL query result for the second session is below:
BEGIN
SELECT users.id AS users_id, users.name AS users_name, users.fullname
AS users_fullname
FROM users
WHERE users.name = ?
LIMIT 1 OFFSET 0
('fred',)
DELETE FROM users WHERE users.id = ?
(1,)
COMMIT
The first query is wasteful for what I'm trying to achieve, which is
to delete the user whose user.name I *know* is there (even if I didn't
know, I'd be content to catch the exception).
What I can't figure out is... with the second session, what is the
correct/best way to do a simple deletion without requiring a mapped
orm object to give to session.delete? Do I need to leave the orm
world to do this? I would rather not resort to session.execute if at
all possible.
--
You received this message because you are subscribed to the Google Groups
"sqlalchemy" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/sqlalchemy?hl=en.