将关系转换为查询对象

时间:2012-08-07 08:40:23

标签: python mysql sqlalchemy flask flask-sqlalchemy

假设我在表User和Car之间有很多关系。

使用

时效果很好
User.query.filter_by(name='somename').all().cars

Car.query.filter_by(vin='xxxxxx').all().users

我创建了将BaseQuery转换为xml对象的函数,因此我需要从Car.query.filter_by(vin='xxxxxx').all().users中提取BaseQuery。

有没有办法做到这一点?

1 个答案:

答案 0 :(得分:4)

老实说,我不知道你提供的代码示例是如何实际工作的,因为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(...)