ffu*_*tes 6 python mysql sqlalchemy pyramid
问题是尝试使用Pyramid上的SQLAlchemy从数据库中检索具有关系的对象.我想要的主要是创建我需要从数据库中检索的对象,以完成网页所需的数据.
当我尝试访问url/poll/{id}(使用有效的轮询ID,例如:/ poll/1)来获取页面时,我收到此错误:AttributeError:'Query'对象没有属性'_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
Run Code Online (Sandbox Code Playgroud)
这是代码中给我带来麻烦的一部分.调试器指向倒数第二行(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}
Run Code Online (Sandbox Code Playgroud)
提前致谢!
uni*_*rio 10
qinst是一个Query,而不是一个Question.你可能想要:
qinst = session.query(Question).filter_by(poll=pinst).one()
Run Code Online (Sandbox Code Playgroud)
要么
qinst = session.query(Question).filter_by(poll=pinst).first()
Run Code Online (Sandbox Code Playgroud)
您还可以在添加backref Question这样你就可以从去Poll到Question:
class Question(Base):
...
poll = relationship(Poll, backref="question")
qinst = pinst.question
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15039 次 |
| 最近记录: |