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 /可是,我想加入这些结果与附加Output
和Production
表格的列(+在Production.flag
上应用过滤器)。
我不知道该怎么做!!!
新手在sqlalchemy,我会感谢任何意见或帮助。