Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/reporting-services/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python slqlachemy通过变量声明连接的加载_Python_Sqlalchemy_Turbogears2 - Fatal编程技术网

Python slqlachemy通过变量声明连接的加载

Python slqlachemy通过变量声明连接的加载,python,sqlalchemy,turbogears2,Python,Sqlalchemy,Turbogears2,假设我有两个模型。说明和问题 class Account(DeclarativeBase): __tablename__ = 'accounts' id = Column(Integer, primary_key=True) user_name = Column(Unicode(255), unique=True, nullable=False) 我的问题是: class Question(DeclarativeBase): __tablename__ = '

假设我有两个模型。说明和问题

class Account(DeclarativeBase):
    __tablename__ = 'accounts'

    id = Column(Integer, primary_key=True)
    user_name = Column(Unicode(255), unique=True, nullable=False)
我的问题是:

class Question(DeclarativeBase):
    __tablename__ = 'questions'

    id = Column(Integer, primary_key=True)
    content = Column(Unicode(2500), nullable=False)
    account_id = Column(Integer, ForeignKey(
    'accounts.id', onupdate='CASCADE', ondelete='CASCADE'), nullable=False)
    account = relationship('Account', backref=backref('questions'))
我得到了一个从提供的问题ID返回json格式问题的方法。 当方法如下所示时,它只返回问题的
id
内容
帐户id

    @expose('json')
    def question(self, question_id):
        return dict(questions=DBSession.query(Question).filter(Question.id == question_id).one())
但是我也需要在json响应中包含帐户的用户名。奇怪的是(至少对我来说)我必须显式地告诉方法查询结果包含与帐户的关系,这样帐户信息就会包含在json响应中:我的意思是这样做

    @expose('json')
    def question(self, question_id):
        result = DBSession.query(Question).filter(Question.id == question_id).one()
        weird_variable = result.account.user_name
        return dict(question=result)
我为什么要做这样的事?这背后的原因是什么?

来自:

默认情况下,所有对象间关系都是延迟加载

换句话说,在其默认配置中,当您获取
问题
时,关系帐户实际上不会加载帐户数据,而是当您访问
问题
实例的
帐户
属性时。这种行为可以控制:

from sqlalchemy.orm import joinedload

DBSession.query(Question).\
    filter(Question.id == question_id).\
    options(joinedload('account')).\
    one()
添加
joinedload
选项将指示查询使用联接同时加载与父级的关系。还提供了其他快速加载技术,其可能的用例和权衡在以下章节中讨论:

默认情况下,所有对象间关系都是延迟加载

换句话说,在其默认配置中,当您获取
问题
时,关系帐户实际上不会加载帐户数据,而是当您访问
问题
实例的
帐户
属性时。这种行为可以控制:

from sqlalchemy.orm import joinedload

DBSession.query(Question).\
    filter(Question.id == question_id).\
    options(joinedload('account')).\
    one()
添加
joinedload
选项将指示查询使用联接同时加载与父级的关系。还提供了其他急切加载技术,其可能的用例和权衡将在下面进行讨论