orm - Flask-SQLAlchemy 中查询表的简写

标签 orm sqlalchemy flask-sqlalchemy

假设我有一个名为 User 的模型和一个名为 followers 的表格:

followers = db.Table(
    'followers',
    db.Column('follower_id', db.Integer, db.ForeignKey('user.id')),
    db.Column('followed_id', db.Integer, db.ForeignKey('user.id'))
)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), index=True, unique=True)
    followed = db.relationship(
        'User',
        secondary=followers,
        primaryjoin=(followers.c.follower_id==id),
        secondaryjoin=(followers.c.followed_id==id),
        backref=db.backref('followers', lazy='dynamic'),
        lazy='dynamic'
    )

查询User模型有两种方法:

  1. db.session.query(User).filter(...).all()
  2. User.query.filter(...).all()

后者被认为是前者的简写,因为它们在功能上相同,但更紧凑。但是,当谈到表格时,followers.query.filter(...).all() 给了我一个错误:

AttributeError: 'Table' object has no attribute 'query'

db.session.query(followers).filter(...).all()的简写吗?或者,如何从 table 对象获取 query 对象?

最佳答案

flask-sqlalchemy 仅在 db.Model 上定义 query,因此虽然您可以对 子类的任何内容执行 Foo.query db.Model,您不能对 Table 实例执行相同操作。

我想你可以对其进行猴子补丁,但我不建议这样做。

关于orm - Flask-SQLAlchemy 中查询表的简写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45343875/

相关文章:

javascript - JS Sequelize "Where Related"查询?

laravel - 向 User Eloquent ORM 模型添加字段

python - Flask SQLAlchemy 关联表 : error creating backref

插入后Python SQLAlchemy获得返回ID

postgresql - 用于数据库连接的 Flask before_request 和 teardown_request

python - 使用蓝图时 Flask Sqlalchemy 循环导入

php - 预加载参数 - laravel

orm - 使用Doctrine ORM的表命名约定

python - SQLAlchemy 中的一对多+一对关系?

python - Flask - 在应用程序上下文之外工作