我正在尝试创建一个新对象并在其上附加一个已经存在的对象,但是我收到一个错误“ sqlalchemy.exc.InvalidRequestError:Object”已附加到会话“ 4”(这是“ 5')“
这是我的模特:
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True,autoincrement=True)
username = Column(String(20), nullable=False)
password = Column(String(30), nullable=False)
name = Column(String(300), nullable=False)
conversation = relationship('Conversation',backref ='users',lazy='subquery')
class Response(Base):
__tablename__ = 'responses'
id = Column(Integer, primary_key=True,autoincrement=True)
response = Column(String(500), nullable=False)
intent_id = Column(Integer, ForeignKey('intents.id'))
class Pattern(Base):
__tablename__ = 'patterns'
id = Column(Integer, primary_key=True,autoincrement=True)
pattern = Column(String(300), nullable=False)
intent_id = Column(Integer, ForeignKey('intents.id'))
class Conversation(Base):
__tablename__ = 'conversations'
id = Column(Integer, primary_key=True,autoincrement=True)
question = Column(String(500), nullable=False)
classify = Column(Float(5))
date = Column(DateTime, default=datetime.datetime.now())
response_id = Column(Integer, ForeignKey('responses.id'))
response = relationship('Response', lazy='subquery')
intent_id = Column(Integer, ForeignKey('intents.id'))
intent = relationship('Intent', lazy='subquery')
user_id = Column(Integer, ForeignKey('users.id'))
user = relationship('User', lazy='subquery')
class Intent(Base):
__tablename__ = 'intents'
id = Column(Integer, primary_key = True,autoincrement=True)
tag = Column(String(50), nullable = False)
context_filter = Column(String(50), nullable = True)
context_set = Column(String(50), nullable = True)
patterns = relationship('Pattern',backref ='intents', lazy='subquery')
responses = relationship('Response',backref='intents', lazy='subquery')
我正在尝试从数据库中获取意图并放入新的对话对象中,这是我正在尝试执行的操作,但它不起作用:
cv = Conversation()
cv.user = getSingleUser(question['idUser'])
cv.question = question['question']
cv.classify = classify[1]
responseDict = chatBotResponse(question['question'])
cv.response = getSingleResponse(responseDict['id'])
intent = getIntentByName(classify[0])
cv.intent = intent
insertEdit(cv)
//数据库类
from sqlalchemy.orm import sessionmaker
DBSession = sessionmaker(bind=engine)
def getSingleUser(id):
session = DBSession()
user = session.query(User).filter_by(id=id).first()
session.close()
return user
def getSingleResponse(id):
session = DBSession()
response = session.query(Response).filter_by(id=id).first()
session.close()
return response
def getIntentByName(name):
session = DBSession()
intent = session.query(Intent).filter_by(tag=name).first()
return intent
def insertEdit(obj):
session = DBSession()
session.add(obj)
session.commit()
session.close()
但是我得到的只是
sqlalchemy.exc.InvalidRequestError:对象“意图为0x226e9ffe5f8”已附加到会话“ 4”(此为“ 5”)
有人可以指出我做错了什么,而做我需要的最好方法是什么?
谢谢!