0

Postというモデルがあり、これにはis_answerというブール値フィールドがあります。 のis_answerフィールドがTrueの場合、それは「質問」です。そうでなければ、それは "答え"です。Flask-SQLAlchemyで自己参照型の一対多関係を作成するには?

「質問」には「回答」が1つ多くありますが、「回答」には1つの「質問」しかありません。 「質問」と「回答」の両方が本質的にPostであるという事実のために、私はその関係が自己参照でなければならないと考えています。ここで

は、私が試したものです:

class Post(db.Model): 
    __tablename__ = 'posts' 
    id = db.Column(db.Integer, primary_key=True) 
    is_question = db.Column(db.Boolean) 
    post_id = db.Column(db.Integer, db.ForeignKey('posts.id')) 
    question = db.relationship('Post', backref=db.backref('answer', lazy='dynamic'), uselist=False, lazy='dynamic') 

エラーは次のとおりです。

ArgumentError: Post.question and back-reference Post.answer are both of the same direction symbol('ONETOMANY'). Did you mean to set remote_side on the many-to-one side ?

答えて

2

あなたは自己参照関係を作成するためのremote_side引数を追加する必要があります。より詳しい情報はdocumentaionにあります。

UPDATED:post_idフィールドがNullであるかどうかを確認することで、質問と回答を判別できるので、ブール値フラグis_questionは必要ありません。

class Post(Base): 
    __tablename__ = 'posts' 
    id = Column(Integer, primary_key=True) 
    post_id = Column(Integer, ForeignKey('posts.id')) 
    question = relationship('Post', remote_side=[id], backref=backref('answers'), uselist=False) 

テスト:

session.add(
    Post(
     id=1, 
     post_id=None 
    ) 
) 
session.add(
    Post(
     id=2, 
     post_id=1 
    ) 
) 

session.add(
    Post(
     id=3, 
     post_id=1 
    ) 
) 

session.commit() 

question = session.query(Post).get(1) 
print question.answers # output [post2, post3] 
answer = session.query(Post).get(2) 
print answer.question.id # output 1 

# Receive all answers 
print session.query(Post).filter(Post.post_id.isnot(None)).all() 
1

あなたは、以下の質問を使用して、テーブルに答えることができます。

class Answer(Base): 
     __tablename__="answers" 
     id = Column(Integer, primary_key=True) 
     mcq_id = Column(Integer,ForeignKey('questions.id')) 
     answer_text = Column(Text()) 
     is_correct = Column(Boolean, nullable=False, default=False) 

    class Question(Base): 
     __tablename__="questions" 
     id = Column(Integer, primary_key=True) 
     question_text = Column(Text()) 
     answer_explanation = Column(Text()) 
     answer_choices = relationship('Answer', 
            primaryjoin="and_(Question.id == Answer.mcq_id)", 
            cascade="all, delete-orphan", 
            foreign_keys=[Answer.mcq_id]) 
# If you have more than one answers then define this function in your model. 
    def has_more_than_one_correct_answer(self): 
     count = 0 
     for choice in self.answer_choices: 
      if choice.is_correct: 
       count = count + 1 
     if count > 1: 
      return True 
     else: 
      return False 

2つのテーブルの関係を見ることができます。また、sqlalchemyを使用している場合は、joinedloadまたはjoinedload_allを使用して関係にアクセスできます。

関連する問題