【问题标题】:How to find the set of entities more recent than the last one with children如何找到比上一个有孩子的实体更新的实体集
【发布时间】:2010-11-15 20:02:33
【问题描述】:

我有两个这样指定的 SQLAlchemy 模型对象:

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")

我正在寻找一个查询,该查询将仅返回那些 spec_date 大于具有实例的最近一个对象的 Spec 对象。例如,给定这样的对象:

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')

我希望我的查询仅返回 Spec 3。Spec 2 不符合条件,因为它有实例。 Spec 1 不符合条件,因为它比 Spec 2 旧。

我该怎么做?

【问题讨论】:

    标签: python orm sqlalchemy


    【解决方案1】:

    我没有测试这段代码,因为我很确定它会工作并且设置环境是开销。

    在普通的 SQL 中,可以使用子查询来执行此操作。在 sqlalchemy 中,以这种方式创建子查询:

    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()
    

    在这里,我们加入了两个表,因此只考虑带有 SpecInstances 的 Spec,然后我们按日期对它们进行排序,以便最新的在最上面,并且只取第一个 - 最年轻的实例 - 我们只需要它的日期。这不会被执行 - 它将被准备为子查询:

    session.query(Spec)\
           .join((sq, Spec.spec_date>sq.c.most_recent))
    

    这很简单。小心在连接结构上加上双括号,并在 sq 的第二个查询中包含 .c,因为 'most_recent' 将是动态列查找。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-12-19
      • 2011-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-10
      相关资源
      最近更新 更多