首页 > 解决方案 > 我怎样才能知道如何获得正确的pk?

问题描述

我是编程新手,正在练习制作投票应用程序。但我坚持试图让每个选择的百分比投票,就像这样:

模型.py:


class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

    def __str__(self):
        return self.question_text

    def was_published_recently(self):
        now = timezone.now()
        return now - datetime.timedelta(days=1) <= self.pub_date <= now
    was_published_recently.admin_order_field = 'pub_date'
    was_published_recently.boolean = True
    was_published_recently.short_description = 'Published recently?'


class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

    def __str__(self):
        return self.choice_text

视图.py:

class IndexView(ListView):
    template_name = 'posts/index.html'
    context_object_name = 'latest_question_list'

    def get_queryset(self):
        """
        Return the last five published questions (not including those set to be
        published in the future).
        """
        return Question.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')[:5]


class DetailView(DetailView):
    model = Question
    template_name = 'posts/detail.html'


class ResultsView(DetailView):
    model = Question
    template_name = 'posts/results.html'

    def get_context_data(self, *args, **kwargs):
        context = super(ResultsView, self).get_context_data(*args, **kwargs)
        q = Question.objects.get(pk=self.kwargs['pk'])
        total = q.choice_set.aggregate(Sum('votes'))

        percentage = q.choice_set.get(
            pk=self.kwargs.get('pk')).votes / total['votes__sum']

        context['total'] = total['votes__sum']
        context['percentage'] = percentage

        return context


def vote(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    try:
        selected_choice = question.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        # Redisplay the question voting form.
        return render(request, 'posts/detail.html', {
            'question': question,
            'error_message': "You didn't select a choice.",
        })
    else:
        selected_choice.votes += 1
        selected_choice.save()
        # Always return an HttpResponseRedirect after successfully dealing
        # with POST data. This prevents data from being posted twice if a
        # user hits the Back button.
        return HttpResponseRedirect(reverse('posts:results', args=(question.id,)))
P

问题是,当我试图获得百分比时,我得到了错误的 pk,并且不知道如何使它正确。在这种情况下,我试图获得每个选择票并除以总票数,总票数很好,但无法获得每个选择的价值。

有小费吗?有没有更简单的方法来做到这一点?

标签: pythondjangopercentage

解决方案


您可以使用annotate来计算每个Choice. 投票数是一个整数,因此您需要将Cast其设置为浮点数,以便使用浮点除法而不是整数除法

from django.db.models.functions import Cast
from django.db.models import Sum, FloatField

question = Question.objects.get(pk=self.kwargs['pk'])
total_votes = question.choice_set.aggregate(Sum('votes'))['votes__sum']
choices = question.choice_set.annotate(
    percentage=Cast('votes', output_field=FloatField()) / total_votes
)

for choice in choices:
    print(choice, choice.percentage)

推荐阅读