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.