【发布时间】:2021-06-25 06:56:57
【问题描述】:
我正在用 Python 构建一个“测验应用程序”,我需要将结果存储在 SQL 数据库中。我想使用 SQLAlchemy Python 库与数据库进行交互。
我的应用程序的每个用户将被问到从预先确定的 100 个可能问题中随机选择的 3 个问题。每个问题只能回答“是”或“否”(即True 或False)。
我将答案存储在一个定义如下的表中:
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")
在所有用户完成测验后,我计算某个问题被用户回答的次数:
tot_each_question = (db_session
.query(Answer.question_id,
count_questions.label("tot_answers_for_question"))
.group_by(Answer.question_id)
)
我还可以计算某个问题被用户回答“是”(即True)的次数:
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)
)
如何使用 SQLAlchemy 计算用户回答“是”的每个问题的百分比? 我可以使用基本的 Python 字典轻松做到这一点:
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
但我更喜欢使用 SQLAlchemy 功能来获得相同的结果。是否可以在 SQLAlchemy 中做到这一点?在 SQLAlchemy 中这样做是否方便高效,或者我基于 Python 字典的解决方案是否会更好?
【问题讨论】:
标签: python sql sqlalchemy