Flask-SQLAlchemy-您可以在模型中进行查询吗? [英] Flask-SQLAlchemy– Can you make a query within a model?

查看:147
本文介绍了Flask-SQLAlchemy-您可以在模型中进行查询吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个使用Flask-SQLAlchemy的Flask Web应用程序,并且我还在考虑使用Flask-Login来管理会话并保护某些视图.

I'm building a flask webapp which uses Flask-SQLAlchemy, and I'm also considering using Flask-Login to take care of sessions and to protect certain views.

Flask-Login需要某些方法,我认为这些方法对应用程序的各个部分有用(特别是is_authenticated()is_active().),但是,在所有示例中,我都看到这些方法只是返回了固定值.例如,如果要检查该用户是否在表中确实有一个条目(我正在使用LDAP登录,因此希望用户即使在尽管我需要查看它们是否在表中,但它们在表中没有任何条目.

Flask-Login requires certain methods which I see as useful for various parts of the app (specifically, is_authenticated() and is_active(). However, in all of the examples I've seen these methods just return something fixed. What if I want to make a query on the database. For example, if I want to check if that user actually has an entry in the table (I'm using LDAP to log in, so want users to be able to log in even if they haven't got an entry in the table, although I need to see if they are there).

但是我不知道是否可以从定义它的类中对表本身进行查询?还是应该将这些函数放在其他位置(即使用户类中的flask-login需要使用这些方法)?

But I don't know if it's possible to make a query on the table itself from within the class which defines it? Or should I place these functions elsewhere (even though the methods are needed by flask-login within the user class)?

推荐答案

可以.通常 Session.object_session 是获得会话并执行查询的好方法:

You can. Usually the Session.object_session is a good way to get a session and perform a query:

class MyModel(Base):
    __tablename__ = u'model_table'
    id = Column(Integer, primary_key=True)
    # ...

    def my_method(self):
       session = Session.object_session(self)
       qry = session.query(...).filter(...)
       # ...

这篇关于Flask-SQLAlchemy-您可以在模型中进行查询吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆