纯粹的关系方式需要使用子查询来获取与父级相关的“最新”或“最大”值,然后将其与集合的成员等同。这意味着如果在确定“最新”的列上放置索引,您将获得最佳结果:
from sqlalchemy import *from sqlalchemy.orm import *engine = create_engine('sqlite:///:memory:', echo='debug')m = metaData()parent = Table('parent', m, Column('id', Integer, primary_key=True))child = Table('child', m, Column('id', Integer, primary_key=True), Column('parent_id', Integer, ForeignKey('parent.id')), Column('sortkey', Integer) )m.create_all(engine)class Parent(object): def __init__(self, children): self.all_c = childrenclass Child(object): def __init__(self, sortkey): self.sortkey = sortkeylatest_c = select([func.max(child.c.sortkey)]). where(child.c.parent_id==parent.c.id). correlate(parent). as_scalar()mapper(Parent, parent, properties={ 'all_c':relation(Child), 'latest_c':relation(Child, primaryjoin=and_( child.c.sortkey==latest_c,child.c.parent_id==parent.c.id ), uselist=False )})mapper(Child, child)session = sessionmaker(engine)()p1, p2, p3 = Parent([Child('a'), Child('b'), Child('c')]), Parent([Child('b'), Child('c')]), Parent([Child('f'), Child('g'), Child('c')])session.add_all([p1, p2, p3])session.commit()assert p1.latest_c.sortkey == 'c'assert p2.latest_c.sortkey == 'c'assert p3.latest_c.sortkey == 'g'
另外,您可以在某些平台上使用LIMIT,因为可以避免聚合,并且可以在其主键上加入集合项,因此可以产生更快的结果:
latest_c = select([child.c.id]). where(child.c.parent_id==parent.c.id). order_by(child.c.sortkey.desc()). limit(1). correlate(parent). as_scalar()mapper(Parent, parent, properties={ 'all_c':relation(Child), 'latest_c':relation(Child, primaryjoin=and_( child.c.id==latest_c,child.c.parent_id==parent.c.id ), uselist=False )})
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)