【发布时间】:2017-07-27 07:18:24
【问题描述】:
假设我有一个名为 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模型有两种方式:
db.session.query(User).filter(...).all()User.query.filter(...).all()
后者被认为是前者的简写,因为它们在功能上相同但更紧凑。但是,当谈到桌子时,followers.query.filter(...).all() 给了我一个错误:
AttributeError: 'Table' 对象没有属性 'query'
db.session.query(followers).filter(...).all() 有简写吗?或者,如何从table 对象中获取query 对象?
【问题讨论】:
标签: orm sqlalchemy flask-sqlalchemy