django - 如何通过投票对答案对象进行排序?
问题描述
在这里,我想通过他们的投票来排序问题的答案。投票率较高的答案将位于顶部,但如果它已接受答案,那么它将像 StackOverflow 一样保持在顶部。我怎么能在这里做呢?
意见
class DetailQuestionView(LoginRequiredMixin, View):
template_name = 'post_detail.html'
def get(self, request, **kwargs):
question = get_object_or_404(Question, pk=kwargs['pk'])
"""checking if the current user has voted on the question or not"""
q_voted = question.question_votes.filter(user=request.user, question=question).exists()
"""getting the list of answers which are voted by the current user"""
answers = question.answers.all().order_by('votes') ## how ??
a_voted_list = [answer for answer in answers if answer.answer_votes.filter(user=request.user, answer=answer)]
context = {
'question': question,
'voted': q_voted,
'a_voted_list': a_voted_list,
'answers': answers
}
楷模
class Answer(CommonInfo):
question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='answers')
ans = models.TextField()
user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name='user_answers')
is_accepted = models.BooleanField(default=False)
class AnswerVote(CommonInfo):
answer = models.ForeignKey(Answer, on_delete=models.CASCADE, related_name='answer_votes')
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_votes_ans')
解决方案
我想你正在寻找这样的东西。它可能无法按原样工作。但我想你明白了。
from django.db.models import Count
answers = Answer.objects.filter(question=question) \
.annotate(answer_vote=Count('answer_vote')) \
.order_by('-answer_vote')
编辑:is_accepted
通过投票
首先订购应该有效。
.order_by('-is_accepted', '-answer_vote')
推荐阅读
- firebase - 在 Firestore 中使用身份验证限制特定对象键值
- c# - 如何删除当前用户的 localappdata 中的目录
- c++ - 如何获取双精度的小数部分并将其转换为整数?(c++)
- scripting - Netsuite 已在预定脚本中保存搜索 无结果
- php - laravel 单个帖子未在 livewire 中显示
- ethereum - Solidity ERC-721 错误:返回错误:执行已恢复
- swift - PHImageManager 请求精确大小的图像并不总是有效
- postgresql - 如何使用 database-rider 将 DataSet 插入表中,其列定义为 GENERATED ALWAYS?
- python - 如何从 Pandas DF 中删除特殊字符?
- windows - 使用 Golang 进行 DLL 注入(CreateRemoteThread)