0

I would like to create a simple questions table, which has an answers table referenced to it. For each question I create, I should be able to add at least one answer to it. The answer(s) will be stored in a separate table which will also have the id of the question via foreign key. This I what I have so far:

class Qns(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    qn = db.Column(db.String, nullable=False)
    qn_type = db.Column(db.String, nullable=False)
    answers = db.relationship('Ans', backref='qn')

    def __init__(self, qn, qn_type):
        self.qn = qn
        self.qn_type = qn_type

    def __repr__(self):
        return '<Ques %r>' % self.data

class Ans(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    ans = db.Column(db.String, nullable=False)

    qn_id = db.Column(db.Integer, db.ForeignKey('qns.id'), nullable=True, index=True)

    def __init__(self, qn_id, ans):
        self.qn_id = qn_id
        self.ans = ans

    def __repr__(self):
        return '<Ans %r>' % self.data

@app.route('/', methods=['POST', 'GET'])
def index():
    if request.method == 'POST':
        qn = request.form['qn']
        qn_type = request.form['type']        
        new_qn = Qns(qn=qn, qn_type=qn_type)

        ans = request.form['ans']
        new_ans = Ans(ans=ans)        
        try:
            new_qn.answers.append(new_ans)
            db.session.add(new_qn)
            db.session.commit()
            return redirect('/')
        except:
            return 'Error adding values to DB'
    else:
        return render_template('qns.html')

However, I am getting the error TypeError: __init__() missing 1 required positional argument: 'qn_id' from the line new_ans = Ans(ans=ans). I have followed the answer from here but to no avail. How am I able to get the id of the question and add it to my answer table? Thanks in advance.

mhfour
  • 255
  • 2
  • 8
  • 19
  • Looks line in the __init__ of Ans class, you take in the question id and then the answer. You should be able to get rid of your type error by simply supplying the question id in the object creation of you Ans class. – Anirudh Panchangam Nov 17 '19 at 14:43
  • @AnirudhPanchangam can't believe i did realize that. thanks alot! btw, i would like to add more that one answer. currently i can only add one, how can i achieve this? – mhfour Nov 17 '19 at 14:58
  • I believe inserting more answers with the same question id should help. To do this , you may need to globally cache the question id's so that each of those answers go into the table under the correct quesion id as the Foreign Key – Anirudh Panchangam Nov 17 '19 at 14:59
  • @AnirudhPanchangam would you be able to provide with a code i can follow? – mhfour Nov 17 '19 at 15:13

0 Answers0