老实说,我不明白你给出的代码样本实际上是如何工作的,因为Query.all()
返回一个列表。所以[].users
应该会产生一个错误。
在任何情况下,有以下几个选项:
# 1: this should be fine
qry1 = Car.query.join(User, Car.users).filter(User.name=='you')
# 1: this will probably not work for you, as this is not one query, although the result is a Query instance
usr1 = User.query.filter_by(name='you').one()
qry2 = Car.query.with_parent(usr1)
# 3: you might define the relationship to be lazy='dynamic', in which case the query object instance will be returned
from sqlalchemy.orm.query import Query
class Car(Base):
__tablename__ = 'cars'
id = Column(Integer, primary_key=True)
vin = Column(String(50), unique=True, nullable=False)
users = relationship(User, secondary=user_cars,
#backref='cars',
backref=backref('cars', lazy="dynamic"),
lazy="dynamic",
)
qry3 = Car.query.filter_by(name="you").one().cars
assert isinstance(qry3, Query)
查看选项-3在这里更多的信息:orm.relationship(...)
来源
2012-08-07 11:08:47
van