2016-12-02 91 views
0

我有一組看起來像表:SQLAlchemy的:許多到許多加盟場,其中場= max和額外的字段

Inputs ========= Parts ========= Outputs 
     (n, m)  ||  (n, m) 
        || 
       (n, m) 
        || 
        || 
       Productions 

class Input(DeclarativeBase): 
    __tablename__ = 'inputs' 
    id = Column(Integer, primary_key=True, autoincrement=True) 
    some_attr1 = Column(Unicode(length) 
    some_attr2 = Column(Unicode(length) 

class Output(DeclarativeBase): 
    __tablename__ = 'outputs' 
    id = Column(Integer, primary_key=True, autoincrement=True) 
    some_attr1 = Column(Unicode(length) 
    some_attr2 = Column(Unicode(length) 
    extra_attr1 = Column(Unicode(length) 
    parts = relationship('Part', backref='output', 
         passive_deletes='all', 
         passive_updates=True) 

class Part(DeclarativeBase): 
    __tablename__ = 'parts' 
    id = Column(Integer, primary_key=True, autoincrement=True) 
    id_input = Column(ForeignKey('inputs.id')) 
    id_output = Column(ForeignKey('outputs.id')) 
    extra_attr = Column(Unicode(length)) 

class Production(DeclarativeBase): 
    __tablename__ = 'productions' 
    id = Column(Integer, primary_key=True, autoincrement=True) 
    date = Column(DateTime, default=get_current_time) 
    flag = Column(Boolean) 
    other_attr1 = Column(Unicode(length)) 
    parts = relationship('Parts', 
         secondary="productionsteps", 
         backref=backref("productions", lazy='dynamic')) 

productionsteps = Table('productionsteps', 
         BASE.metadata, 
         Column('id_production', 
           Integer, 
           ForeignKey('productions.id)), 
         Column('id_part', 
           Integer, 
           ForeignKey('parts.id')), 
         UniqueConstraint('id_production', 
             'id_part', 
             name='uix_productionsteps')) 

我想查詢每個輸出子集的最新「作品」 (生成與輸出關聯的一組零件),其中生產日期低於DATE1且生產標誌等於BOOL1。

1 /獲取最新生產的每一個輸出的年紀比DATE1

subquery1 = (
    session.query(Output.id.label("id_output"), 
        func.max(Production.date).label("max_date")) 
      .join(Part, Production.parts) 
      .join(Output, Part.output) 
      .filter(and_(Output.some_attr1 == attr1, 
         Output.some_attr2 == attr2, 
         Production.date<=DATE1)) 
      .group_by(Output.id) 
      .subquery() 
) 

OK,那查詢似乎工作...

2 /可是,我想加入這些結果與附加OutputProduction表格的列(+在Production.flag上應用過濾器)。

我不知道該怎麼做!!!

新手在sqlalchemy,我會感謝任何意見或幫助。

回答

0

解決與查詢:

subquery2 = (
    session.query(Production.id, 
        Output.extra_attr1, 
        Production.other_attr1) 
      .join(Part, Production.parts)    
      .join(Output, Part.output) 
      .filter(and_(subquery1.c.max_date == Productions.date, 
         subquery1.c.id_output == Output.id, 
         Production.flag==BOOL1)) 
      .all() 
    )