我正在尝试为测验创建一个高分统计表/列表,该表/列表应该显示对要被猜测的人的正确猜测的百分比(或总数)。为了进一步阐述,这些是使用的模型。
测验模型:
class Quiz(models.Model):
participants = models.ManyToManyField(
User,
through="Participant",
through_fields=("quiz", "correct_user"),
blank=True,
related_name="related_quiz",
)
fake_users = models.ManyToManyField(User, related_name="quiz_fakes")
user_quizzed = models.ForeignKey(
User, related_name="user_taking_quiz", on_delete=models.CASCADE, null=True
)
time_started = models.DateTimeField(default=timezone.now)
time_end = models.DateTimeField(blank=True, null=True)
final_score = models.IntegerField(blank=True, default=0)
这个模型也有一些属性;我认为它们与手头的问题无关。
参与者模型:
class Participant(models.Model): # QuizAnswer FK -> QUIZ
guessed_user = models.ForeignKey(
User, on_delete=models.CASCADE, related_name="clicked_in_quiz", null=True
)
correct_user = models.ForeignKey(
User, on_delete=models.CASCADE, related_name="solution_in_quiz", null=True
)
quiz = models.ForeignKey(
Quiz, on_delete=models.CASCADE, related_name="participants_in_quiz"
)
@property
def correct(self):
return self.guessed_user == self.correct_user
为了迭代我正在尝试做的事情,我将尝试解释我认为这应该如何工作:
- 对于 a
User
inUser.objects.all()
,找到等于(来自模型)participant
的所有对象user.id
correct_user
participant
- 对于每个
participant
对象,评估 ifcorrect_user
==guessed_user
participant
将上述比较True
针对 的每个对象求和User
,由字段表示sum_of_correct_guesses
- 返回一个查询集,包括所有带参数的用户 [
User
,sum_of_correct_guesses
]
^现在理想情况下应该是percentage_of_correct_guesses
,但这是事后的想法,应该很容易通过sum_of_correct_guesses
对该人的猜测进行 / 和 n 次来改变。
现在我什至为一个人制作了一些伪代码,以向自己大致说明它应该如何使用 python 算法工作
# PYTHON PSEUDO QUERY ---------------------
person = get_object_or_404(User, pk=3) # Example-person
y = Participant.objects.filter(
correct_user=person
) # Find participant-objects where person is used as guess
y_corr = [] # empty list to act as "queryset" in for-loop
for el in y: # for each participant object
if el.correct: # if correct_user == guessed_user
y_corr.append(el) # add to queryset
y_percentage_corr = len(y_corr) / len(y) # do arithmetic division
print("Percentage correct: ", y_percentage_corr) # debug-display
# ---------------------------------------------
我尝试过的(到目前为止没有成功)是将 ExtensionWrapper 与Count()
对象Q
一起使用:
percentage_correct_guesses = ExpressionWrapper(
Count("pk", filter=Q(clicked_in_quiz=F("id")), distinct=True)
/ Count("solution_in_quiz"),
output_field=fields.DecimalField())
all_users = (
User.objects.all().annotate(score=percentage_correct_guesses).order_by("score"))
非常感谢有关如何执行此操作的任何帮助或资源指示:))