2017-11-18 6 views
0

어린이에게 필 터 필터가 작동하지 않습니다. 나는 그것이 틀린 방식으로 행해지는지 확실치 않습니다.플라스크 sqlalchemy - 다 대 다 관계 - 하위 레벨 필터링

country.py

product_country = Table('product_country', Base.metadata, 
    Column('product_id', Integer, ForeignKey('product.id'), primary_key=True), 
    Column('country_id', Integer, ForeignKey('country.id'), primary_key=True) 
) 

class Country(Base): 
    __tablename__="country" 
    id = Column(Integer, primary_key=True) 
    name = Column(String(200)) 
    products = relationship(Product, secondary=product_country, backref='countries') 

product.py

는 SQLAlchemy의 검색
class Product(Base): 
    __tablename__="product" 
    id = Column(Integer, primary_key=True) 
    color = Column(Integer) 
    .... 

: 무슨 일이 내가 원하는

country = s.query(Country).join(Country.products).filter(Country.id==1).filter(Product.color==1).first() 

글쎄, 내가 아이디 = 1 국가를 얻을 수있다 그러나 country.products 목록에는 color = 1 인 제품 만 있으면되지만 국가에 할당 된 모든 제품이 있습니다. 제발 도와주세요. 고마워요

+0

'Product'의 더 완전한 스 니펫을 게시 할 수 있습니까?'Product.color' 정의 방법을 볼 수 없기 때문에 가능합니다. – bgse

+0

@bgse - Color가 정의 된 Product 클래스를 업데이트했습니다. 그러나 그것은 색의 정의에 관한 것이 아닙니다. 당신은 sqlalchemy 쿼리에서 id로 색상을 대체 할 수 있으며, 동일한 문제가 있습니다. – user4206969

답변

0

그건 오해입니다. 좋은 이유로, 관계로드가 조회와 구별됩니다. 즉, 사용했던 조인은 열정적으로 관계를로드하는 데 사용되지 않습니다. 열의 부하 조인이 contains_eager() 인 쿼리에 지시하고 이해하려면 "the zen of joined eager loading"을 읽고 시도하는 방법에 대한 예제는 "Using contains_eager() to load a custom-filtered collection result"을 참조하십시오. 귀하의 경우 귀하의 질문에

options(contains_eager(Country.products)) 

을 추가하십시오.

+0

설명해 주셔서 감사합니다. – user4206969