python - 我怎样才能知道如何获得正确的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,并且不知道如何使它正确。在这种情况下,我试图获得每个选择票并除以总票数,总票数很好,但无法获得每个选择的价值。
有小费吗?有没有更简单的方法来做到这一点?
解决方案
您可以使用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)
推荐阅读
- php - PHP如何更新数据库表中不同列中上传的多个文件
- c# - 访问静态非单一行为类
- exception - 拓扑发生异常时跳过记录
- database - 如何在不导入的情况下将excel电子表格导入anylogic数据库,即在主启动时使用代码
- excel - 引用动态工作簿名称 - VBA
- javascript - 在浏览器中实现 gzip 文件的回退
- azure-web-app-service - 在 azure App Service 上连接另一台服务器
- database - Oracle DB 计划将表导出到 .CSV 文件
- active-directory - 无法在使用 Powershell 的脚本中确定密码使用期限
- python - 为什么代理服务器使用我的私有 IP?