如何在Sqlalchemy中为各种模型编写通用的get_by_id()方法?
我将 pylons 与 sqlalchemy 一起使用。我有几个模型,发现自己一遍又一遍地写这样的代码:
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()
既然模型都是扩展类Base
,有没有办法定义一个通用的get_by_id()
方法?
所以我可以将它用作:
quesiton = Question.get_by_id(question_id)
answer = Answer.get_by_id(answer_id)
...
user = User.get_by_id(user_id)
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果 id 是您的主键列,您只需执行以下操作:
如果该实例已在会话中,则这样做的优点是不查询数据库。
If
id
is your primary key column, you just do:which has the advantage of not querying the database if that instance is already in the session.
不幸的是,SQLAlchemy 不允许您在没有相应表声明的情况下子类化
Base
。您可以使用定义 mixin 类 get_by_id
作为类方法,但是您需要为每个类指定它。一个更快但更脏的解决方案是将其猴子修补到
Base
中:这假设您在定义时有一个可用的
session
对象,否则您将每次都需要将其作为参数传递。Unfortunately, SQLAlchemy doesn't allow you to subclass
Base
without a corresponding table declaration. You could define a mixin class withget_by_id
as 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
session
object available at definition-time, otherwise you'll need to pass it as an argument each time.