I’m using pylons with sqlalchemy. I have several models, and found myself wrote such code again and again:
question = Session.query(Question).filter_by(id=question_id).one()
answer = Session.query(Answer).fileter_by(id=answer_id).one()
...
user = Session.query(User).filter_by(id=user_id).one()
Since the models are all extend class Base, is there any way to define a common get_by_id() method?
So I can use it as:
quesiton = Question.get_by_id(question_id)
answer = Answer.get_by_id(answer_id)
...
user = User.get_by_id(user_id)
Unfortunately, SQLAlchemy doesn’t allow you to subclass
Basewithout a corresponding table declaration. You could define a mixin class withget_by_idas a classmethod, but then you’d need to specify it for each class.A quicker-and-dirtier solution is to just monkey-patch it into
Base:This assumes you’ve got a
sessionobject available at definition-time, otherwise you’ll need to pass it as an argument each time.