SQLAlchemy:关系集合延迟加载

时间:2019-05-15 00:14:28

标签: python sqlalchemy

根据SQLAlchemy documentation on relationship loading

  

当第一次在特定对象上访问给定的集合或引用时,将发出一条附加的SELECT语句,以便加载请求的集合。

如何实现加载行为,使得仅加载我访问的关系集合的单个元素,而不是一次加载整个集合?

我听说过deferred column loading;这更像是“延迟行加载”。我不想推迟属性的加载,而是想推迟关系集合元素的加载。

所需的用例:

# Persist instance.
coln = Collection([1, 2, 3])
session.add(coln)
session.commit()

# Test lazy loading.
print('data' in coln.__dict__)
# Lazy loads the entire collection. I'd like only one element.
print(coln.data[1])
# Will output: "True 3". I'd like: "True 1".
print('data' in coln.__dict__, len(coln.__dict__['data']))

类定义和其他后勤工作

from sqlalchemy import Column, Integer, ForeignKey
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship

Base = declarative_base()
engine = create_engine('sqlite:///:memory:')

# Define classes.
class Collection(Base):
    __tablename__ = 'collection'
    id = Column(Integer, primary_key=True)
    data = relationship('Element')

    def __init__(self, list_):
        self.data = [Element(e) for e in list_]

class Element(Base):
    __tablename__ = 'element'
    id = Column(Integer, primary_key=True)
    parent_id = Column(Integer, ForeignKey('collection.id'))
    value = Column(Integer)

    def __init__(self, value):
        self.value = value

    def __repr__(self):
        return 'Element({})'.format(self.value)

# Create schema.
Base.metadata.create_all(engine)

# Create session.
from sqlalchemy.orm import sessionmaker
Session = sessionmaker(bind=engine)
session = Session()

1 个答案:

答案 0 :(得分:1)

使用lazy参数和dynamic值:

data = relationship('Element', lazy='dynamic')

https://docs.sqlalchemy.org/en/13/orm/collections.html#dynamic-relationship