python - How to find the set of entities more recent than the last one with children -
i have 2 sqlalchemy model objects designated thus:
class specinstance(base): spec_id = column(integer, foreignkey('spec.spec_id')) details = column(string) class spec(base): spec_id = column(integer) spec_date = column(datetime) instances = relationship(specinstance, backref="spec", cascade="all, delete, delete-orphan")
i looking query return spec
objects have spec_date greater recent 1 instances. example, given objects these:
spec(spec_id=1, spec_date='2010-10-01') spec(spec_id=2, spec_date='2010-10-02') spec(spec_id=3, spec_date='2010-10-03') specinstance(spec_id=2, details='whatever')
i want query return spec 3. spec 2 ineligible because has instances. spec 1 ineligible because it's older spec 2.
how do this?
i'm not testing code since i'm pretty sure work , setting env overhead.
in plain sql, 1 subquery. in sqlalchemy, subqueries created in manner:
sq = session.query(spec.spec_date.label('most_recent'))\ .join((specinstance, specinstance.spec_id==spec.spec_id))\ .order_by(desc(spec.spec_date))\ .limit(1).subquery()
here, joined 2 tables spec specinstances taken account, order them date latest on top, , take first - youngest instances - , need date. not executed - prepared subquery in:
session.query(spec)\ .join((sq, spec.spec_date>sq.c.most_recent))
which pretty straightforward. careful put double parentheses on join constructs, , include .c in second query on sq, since 'most_recent' dynamic column lookup.
Comments
Post a Comment