首页 > 解决方案 > 如何通过投票对答案对象进行排序?

问题描述

在这里,我想通过他们的投票来排序问题的答案。投票率较高的答案将位于顶部,但如果它已接受答案,那么它将像 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')

标签: djangodjango-modelsdjango-views

解决方案


我想你正在寻找这样的东西。它可能无法按原样工作。但我想你明白了。

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')

推荐阅读