如何在Sqlalchemy中为各种模型编写通用的get_by_id()方法?

发布于 2024-09-17 19:04:00 字数 508 浏览 5 评论 0原文

我将 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

阳光的暖冬 2024-09-24 19:04:00

如果 id 是您的主键列,您只需执行以下操作:

session.query(Foo).get(id)

如果该实例已在会话中,则这样做的优点是不查询数据库。

If id is your primary key column, you just do:

session.query(Foo).get(id)

which has the advantage of not querying the database if that instance is already in the session.

楠木可依 2024-09-24 19:04:00

不幸的是,SQLAlchemy 不允许您在没有相应表声明的情况下子类化Base。您可以使用 定义 mixin 类 get_by_id 作为类方法,但是您需要为每个类指定它。

一个更快但更脏的解决方案是将其猴子修补到Base中:

def get_by_id(cls, id, session=session):
    return session.query(cls).filter_by(id=id).one()

Base.get_by_id = classmethod(get_by_id)

这假设您在定义时有一个可用的session对象,否则您将每次都需要将其作为参数传递。

Unfortunately, SQLAlchemy doesn't allow you to subclass Base without a corresponding table declaration. You could define a mixin class with get_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:

def get_by_id(cls, id, session=session):
    return session.query(cls).filter_by(id=id).one()

Base.get_by_id = classmethod(get_by_id)

This assumes you've got a session object available at definition-time, otherwise you'll need to pass it as an argument each time.

忆悲凉 2024-09-24 19:04:00
class Base(object):
    @classmethod
    def get_by_id(cls, session, id):
        q = session.query(cls).filter_by(id=id)
        return q.one()

Question.get_by_id(Session, question_id)
class Base(object):
    @classmethod
    def get_by_id(cls, session, id):
        q = session.query(cls).filter_by(id=id)
        return q.one()

Question.get_by_id(Session, question_id)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文