gpt4 book ai didi

python - 设置后是否可以抑制 SQLAlchemy 急切/加入的负载?

转载 作者:太空狗 更新时间:2023-10-29 17:03:59 27 4
gpt4 key购买 nike

我有一个案例,在大多数情况下,对象之间的关系是这样的,因此在关系上预先配置一个渴望(加入)的负载是有意义的。但是现在我遇到了一种情况,我真的不想完成急切的加载。

我是否应该从关系中删除连接负载并将所有相关查询更改为在查询位置连接(ick),或者是否有某种方法可以在设置查询后抑制查询中的急切负载?

下面是一个在 User->Address 关系上设置预加载的示例。程序末尾的查询是否可以配置为 NOT eager load?

import sqlalchemy as sa
from sqlalchemy.ext.declarative import declarative_base
import sqlalchemy.orm as orm

##Set up SQLAlchemy for declarative use with Sqlite...
engine = sa.create_engine("sqlite://", echo = True)
DeclarativeBase = declarative_base()
Session = orm.sessionmaker(bind = engine)

class User(DeclarativeBase):
__tablename__ = "users"
id = sa.Column(sa.Integer, primary_key = True, autoincrement = True)
name = sa.Column(sa.String, unique = True)
addresses = orm.relationship("Address",
lazy = "joined", #EAGER LOAD CONFIG IS HERE
)
def __init__(self, Name):
self.name = Name

class Address(DeclarativeBase):
__tablename__ = "addresses"
id = sa.Column(sa.Integer, primary_key = True, autoincrement = True)
address = sa.Column(sa.String, unique = True)
FK_user = sa.Column(sa.Integer, sa.ForeignKey("users.id"))
def __init__(self, Email):
self.address = Email

##Generate data tables...
DeclarativeBase.metadata.create_all(engine)

##Add some data...
joe = User("Joe")
joe.addresses = [Address("joe@example.com"),
Address("joeyjojojs@example.net")]
s1 = Session()
s1.add(joe)
s1.commit()

## Access the data for the demo...
s2 = Session()

#How to suppress the eager load (auto-join) in the query below?
joe = s2.query(User).filter_by(name = "Joe").one() # <-- HERE?
for addr in joe.addresses:
print addr.address

最佳答案

据我所知,您可以在逐个查询的基础上覆盖属性的热切性。这行得通吗?

from sqlalchemy.orm import lazyload
joe = (s2.query(User)
.options(lazyload('addresses'))
.filter_by(name = "Joe").one())
for addr in joe.addresses:
print addr.address

参见 the docs.

关于python - 设置后是否可以抑制 SQLAlchemy 急切/加入的负载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4600683/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com