![](/img/trans.png)
[英]how to commit changes to SQLAlchemy object in the database table
[英]How to commit another object in a property of an object in 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
只需删除session.add(row)
。 因为你使用了session.query
, row
对象已经在你的会话中了。 保存数据足以运行session.commit
函数
你错误地使用了scoped_session
。 这里发生的是每次调用return_a_scoped_session()
它都会返回一个全新的会话,并带有一个全新的引擎。 row
被添加到其他地方的另一个会话中。 (实际上,您发布的代码甚至没有显示其添加的其他位置;我无法使用您发布的代码重现您的错误。)解决方案是修复您的scoped_session
:
engine = create_engine(DB_HOST)
Session = scoped_session(sessionmaker(bind=engine))
def return_a_scoped_session():
return Session()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.