4

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

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Mike Bayer's quote, "SQLAlchemy isn't a framework ... it's a toolkit", seems to sum up my conceptual issues, and Elixir does exactly what I specified above. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.