How to check Flask-SQLAlchemy multiple choice question answer with database

Viewed 615

I'm building a multiple choice question quiz web app using Flask and storing it using sqlite flask-sqlachemy. I have the following database at the moment. I also managed to display the question with below template and routes.

I'm not sure how to check for user answer with correct answer (marked by boolean "correct_answer") and also storing it in the database. I'm thinking of checking it at routes, but I'm not sure how since each set have multiple questions.

class Set(db.Model):
    __tablename__ = 'set'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(140))

    questions = db.relationship('Question', backref='set', lazy='dynamic')
    user_answers = db.relationship('UserAnswer', backref='set', lazy='dynamic')

class Question(db.Model):
    __tablename__ = 'question'
    id = db.Column(db.Integer, primary_key=True)
    set_id = db.Column(db.Integer, db.ForeignKey('set.id'))
    question_text = db.Column(db.Text)

    options = db.relationship('Option', backref='question', lazy='dynamic')
    user_answers = db.relationship('UserAnswer', backref='question', lazy='dynamic')

class Option(db.Model):
    __tablename__ = 'option'
    id = db.Column(db.Integer, primary_key=True)
    question_id = db.Column(db.Integer, db.ForeignKey('question.id'))
    option_text = db.Column(db.Text)
    correct_answer = db.Column(db.Boolean, default=False)

class UserAnswer(db.Model):
    __tablename__ = 'useranswer'
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    set_id = db.Column(db.Integer, db.ForeignKey('set.id'))
    question_id = db.Column(db.Integer, db.ForeignKey('question.id'))
    user_answer = db.Column(db.Integer)
@app.route('/quiz/<set_id>')
def find_question(set_id):
    set = Set.query.filter_by(id=set_id).first_or_404()
    questions = Question.query.filter_by(set_id=set_id).all()

    return render_template('question.html', title='Questions', set=set, questions=questions)
<form action="/quiz_submit" method="POST">
    <ol>
        {% for question in questions %}
        <li id="q{{ question.id }}"">{{ question.question_text }}</li>

            {% for option in question.options %}
            <input type="radio" id="{{ option.id }}" name="{{ question.id }}" value="{{ option.option_text }}">{{ option.option_text }}<br>
            {% endfor %}
            <br>
        {% endfor %}
    </ol>
    <input type="submit" value="Submit" name="Submit"/>
</form>
0 Answers
Related