栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何定义表示集合中最新对象的SQLAlchemy关系?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何定义表示集合中最新对象的SQLAlchemy关系?

纯粹的关系方式需要使用子查询来获取与父级相关的“最新”或“最大”值,然后将其与集合的成员等同。这意味着如果在确定“最新”的列上放置索引,您将获得最佳结果:

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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/661724.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号