2012-08-07 61 views
0

假設我在表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工作正常。

有沒有辦法做到這一點?

回答

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(...)