2017-02-12 233 views
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} 

在此先感謝!

回答

1

qinstQuery而不是Question。你可能想:

qinst = session.query(Question).filter_by(poll=pinst).one() 

qinst = session.query(Question).filter_by(poll=pinst).first() 

你也可以添加在Question一個backref所以你可以去從PollQuestion

class Question(Base): 
    ... 
    poll = relationship(Poll, backref="question") 

qinst = pinst.question 
+0

我想通了。一()或第一()的東西,但我很高興徹底澄清。使用backref似乎更好。 – ffuentes

相關問題