如果您有以下情况:
from django.db import models
class Question(models.Model):
data = models.CharField(max_length=30)
class Answer(models.Model):
question = models.ForeignKey(Question)
def __str__(self):
return str(self.__dict__)
class AnswerVotes(models.Model):
answer = models.ForeignKey(Answer)
helpful = models.SmallIntegerField(default=0)
def __str__(self):
return str(self.__dict__)
它可能看起来有点像解决方法,但为什么不做所有投票的平均帮助。您将在数据库中的原始值介于 0 和 1 之间,而不是 -1 到 1 的范围。在您的情况下,只需将 0.5 视为中间立场,您应该会得到相同的行为。
Answer.objects.annotate(score = Avg('answervotes__helpful'))
{'score': None, 'id': 1, 'question_id': 1}
{'score': 1.0, 'id': 2, 'question_id': 1}
{'score': 0.5, 'id': 3, 'question_id': 1}
{'score': 0.3333333333333333, 'id': 4, 'question_id': 2}
{'score': 0.5, 'id': 5, 'question_id': 3}
{'score': 0.4, 'id': 6, 'question_id': 3}
Answer.objects.annotate(score = Avg('answervotes__helpful')).filter(score__gte=0.5)
{'score': 1.0, 'id': 2, 'question_id': 1}
{'score': 0.5, 'id': 3, 'question_id': 1}
{'score': 0.5, 'id': 5, 'question_id': 3}