I am building a "quiz app" in Python, and I need to store results in a SQL database. I want to use SQLAlchemy Python library to interact with the database.
Each user of my app will be asked 3 randomly selected questions from a predetermined set of 100 possible questions. Each question can only be answered "Yes" or "No" (i.e. True
or False
).
I store answers in a table defined as follows:
class Answer(Base):
__tablename__ = "Answers"
id = Column(Integer, primary_key=True)
user_id = Column(Integer, ForeignKey("Users.id"), nullable=False)
question_id = Column(Integer)
answer = Column(Boolean, nullable=False)
user = relationship("User", back_populates="answers")
After all users complete the quiz, I calculate how many times a certain question was answered by users:
tot_each_question = (db_session
.query(Answer.question_id,
count_questions.label("tot_answers_for_question"))
.group_by(Answer.question_id)
)
I can also calculate how many times a certain question was answered "Yes" (i.e. True
) by users:
tot_true_for_question = (db_session
.query(Answer.question_id,
count_questions.label("tot_true_for_question"))
.filter(Answer.answer == True)
.group_by(Answer.question_id)
)
How do I calculate the percentage each question was answered "Yes" by users, with SQLAlchemy? I can easily do that with basic Python dictionaries:
dict_tot_each_question = {row.question_id: row.tot_answers_for_question
for row in tot_each_question.all()}
dict_tot_true_for_question = {row.question_id: row.tot_true_for_question
for row in tot_true_for_question.all()}
dict_percent_true_for_question = {}
for question_id, tot_answers in dict_tot_each_question.items():
tot_true = dict_tot_true_for_question.get(question_id, 0)
percent_true = tot_true / tot_answers * 100
dict_percent_true_for_question[question_id] = percent_true
But I prefer to use SQLAlchemy functionality to obtain the same result. Is it possible to do that in SQLAlchemy? Would it be convenient and efficient to do that in SQLAlchemy, or would my solution based on Python dictionary be better for any reason?