Reputation: 573
I can't help but think that the number of keystrokes required to do a query in SQLAlchemy is a little on the high side.
DBSession.query(User).filter(...).first()
Is there anything wrong with doing something like this?
DBSession = scoped_session(sessionmaker())
class BaseWithDBSession(object):
def delete(self):
DBSession.delete(self)
@classmethod
def query(cls):
return DBSession.query(cls)
Base = declarative_base(cls=BaseWithDBSession)
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
...
user = User.query().filter(User.id==1).one()
user.delete()
This approach seems a lot neater to me, and it also means I don't have to import DBSession between code files. The downside is that all of my classes are tied to a particular session, but I can't think of any situation in which I would want anything different. I'm trying to think of reasons why I haven't seen this approach before (apart from my inexperience)...
Upvotes: 4
Views: 1648
Reputation: 99530
Well, there are many ways of doing this sort of thing - see Mike Bayer's tongue-in-cheek post about Magic, a "new" ORM. SQLAlchemy postions itself as a toolkit rather than a framework, so that it can be used in different ways according to the needs of different scenarios. For example, there will be scenarios when a single session is not enough.
There are also third-party declarative layers on top of SQLAlchemy - e.g. Elixir. It offers a slightly different way of doing things.
Upvotes: 2