Как я могу узнать, как получить правильный ПК? - PullRequest
1 голос
/ 13 июля 2020

Я новичок в программировании и практикуюсь в создании приложений для опросов. Но я застрял, пытаясь получить процент голосов за каждый выбор, например:

Models.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

Views.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

Проблема заключается в том, что, когда я пытаюсь получить процент, я получаю wronk pk, и не знаю, как это исправить. В этом случае я пытаюсь получить голоса за каждый вариант и разделить его на общее количество голосов, общая сумма работает нормально, но не могу получить значение для каждого варианта.

Есть какие-нибудь советы? есть ли более простой способ сделать это?

1 Ответ

0 голосов
/ 13 июля 2020

Вы можете использовать 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)
...