0
问题在于尝试使用Pyramid上的SQLAlchemy从数据库检索具有关系的对象。我基本上想要的是创建我需要从数据库中检索的对象来完成网页所需的数据。SQLAlchemy AttributeError:'查询'对象在从数据库检索时没有属性'_sa_instance_state'
当我尝试访问url/poll/{id}(使用有效的轮询ID,例如:/ poll/1)来获取页面时,我得到这个错误:AttributeError:'Query'object has no attribute '_sa_instance_state'。什么是错误?
这是模型的相关部分:
class Question(Base):
__tablename__ = 'question'
id = Column(Integer, primary_key=True)
text = Column(String(250))
type_id = Column(Integer, ForeignKey('type.id'))
type = relationship(Type)
poll_id = Column(Integer, ForeignKey('poll.id'))
poll = relationship(Poll)
def __init__(self, text, type, poll):
self.text = text
self.type = type
self.poll = poll
class Option(Base):
__tablename__ = 'option'
id = Column(Integer, primary_key=True)
text = Column(String(250))
question_id = Column(Integer, ForeignKey('question.id'))
question = relationship(Question)
def __init__(self, text, question):
self.text = text
self.question = question
这一个是给我麻烦的代码的一部分。调试器指向倒数第二行(Option对象)。
if request.matchdict['id'] != None:
pinst = session.query(Poll).get(request.matchdict['id'])
typeq = session.query(Type).first()
qinst = session.query(Question).filter_by(poll=pinst)
lopt = session.query(Option).filter_by(question=qinst)
return {'question':qinst, 'arroptions':lopt, 'type':typeq}
在此先感谢!
我想通了。一()或第一()的东西,但我很高兴彻底澄清。使用backref似乎更好。 – ffuentes