如何在sqlalchemy中的对象属性中提交另一个对象?

时间:2016-03-31 10:57:59

标签: python django sqlalchemy

正如标题所说。

以下是代码。

from sqlalchemy import Column, ForeignKey, Integer, String, DateTime, func, Boolean
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm import scoped_session
from sqlalchemy import create_engine
import sqlalchemy.exc
from sqlalchemy import event
from settings import DB_HOST

def return_a_scoped_session():
    engine = create_engine(DB_HOST)
    session_factory = sessionmaker(bind=engine)
    db_session = scoped_session(session_factory)
    return db_session()

Base = declarative_base()


class MyClass(Base):
    """Doc string for MyClass"""
    __tablename__ = 'my_table'
    file_name = Column(String(512), nullable=True)


class Aria2Jobs(Base):
    __tablename__ = 'nh_downloading_jobs'
    id = Column(Integer, primary_key = True)
    file_name = Column(String(512), nullable=True)
    is_verified = Column(Boolean, default=False, nullable=True)

    def check_if_verified(self):
        if self.is_verified:
            # create an instance
            a_job= MyClass(file_name=self.file_name)
            _session = return_a_scoped_session()
            _session.add(a_job)
            _session.commit()
            _session.close()

# event
@event.listens_for(Aria2Jobs.is_verified, 'set')
def send_to_jsonpyes_jobs(target, value, oldvalue, initiator):
    target.check_if_verified()

# error is when I set a property of an object (this property will trigger an event 'set' and the event will try to commit a session.

session = return_a_scoped_session()
row = session.query(Aria2Jobs).first()
row.is_verified = True
session.add(row)

# the error came out
# 
# sqlalchemy.exc.invalidrequesterror object is already attached to session
session.commit()

# How to commit another object in a property of an object?

如何在sqlalchemy中的对象属性中提交另一个对象?

如您所见,当我尝试session.add(row)时,

错误:

sqlalchemy.exc.invalidrequesterror object is already attached to session

我不知道row附加到哪个会话。 我想运行函数check_if_verified

- 最新错误 -

sqlalchemy.exc.InvalidRequestError: Object '<Aria2Jobs at 0x7fad3a635050>' is already attached to session '1' (this is

2 个答案:

答案 0 :(得分:0)

只需删除session.add(row)即可。如果您使用了session.queryrow对象已经在您的会话中。 保存数据足以运行session.commit函数

答案 1 :(得分:0)

您未正确使用scoped_session。这里发生的是每次您致电return_a_scoped_session()它使用全新引擎返回会话时。 row正被添加到其他地方的其他会话中。 (事实上​​,您发布的代码甚至没有显示其添加的其他地方;我无法使用您发布的代码重现您的错误。)解决方案是修复您的{{ 1}}:

scoped_session