2012-08-07 4 views
0

사용자와 자동차 테이블간에 많은 관계가 있다고 가정 해 봅시다. 나는 내가 Car.query.filter_by(vin='xxxxxx').all().users에서 BaseQuery를 추출해야하므로 XML 객체에 BaseQuery 변환 기능을 만들었습니다쿼리 개체와의 관계 변환

User.query.filter_by(name='somename').all().cars 

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

를 사용할 때

그것은 잘 작동합니다.

그렇게 할 방법이 있습니까?

답변

4

Query.all()은 목록을 반환하기 때문에 솔직하게 말하면 코드 예제가 실제로 작동하는 것을 볼 수 없습니다. 그래서 [].users은 오류를 생성해야합니다. 어떤 경우

, 아래의 몇 가지 옵션은 다음과 같습니다 orm.relationship(...)

:

# 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 여기에 더 많은 정보를보기