2017-02-12 9 views
0

問題は、PyramidのSQLAlchemyを使用してデータベースからリレーションシップを持つオブジェクトを取得しようとしています。基本的には、Webページに必要なデータを完成させるためにデータベースから取得する必要のあるオブジェクトを作成することです。SQLAlchemy AttributeError:データベースからの検索時に 'Query'オブジェクトに '_sa_instance_state'属性がありません

有効なポーリングID(例:/ poll/1)を使用してURL/poll/{id}にアクセスしようとすると、このエラーが発生します。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 

この1は私に悩みを与えるコードの一部です。デバッガは、最後の2行目(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

qinstは、ではなく、Queryです。あなたはおそらくしたい:

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

または

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

ので、あなたがPollからQuestionに行くことができます。また、Questionに後方参照を追加することができます。

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

qinst = pinst.question 
+0

私はちょうど(.oneを考え出し)または最初のものだが、徹底的に明確にすることができてうれしい。バックレファレンスを使う方がはるかに良いようです。 – ffuentes

関連する問題