我怎样才能知道如何获得正确的 PK?
How can i find out how to get the right pk?
我是编程新手,正在练习制作投票应用程序。但我一直在尝试获得每个选项的投票百分比,如下所示:
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
问题是,当我试图获得百分比时,我得到了错误的 pk,并且不知道如何使其正确。在这种情况下,我试图获得每个选择的票数并除以总票数,总票数很好,但无法获得每个选择的价值。
有什么建议吗?有更简单的方法吗?
您可以使用 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)
我是编程新手,正在练习制作投票应用程序。但我一直在尝试获得每个选项的投票百分比,如下所示:
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
问题是,当我试图获得百分比时,我得到了错误的 pk,并且不知道如何使其正确。在这种情况下,我试图获得每个选择的票数并除以总票数,总票数很好,但无法获得每个选择的价值。
有什么建议吗?有更简单的方法吗?
您可以使用 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)