Django 1.6 / Python 2.7。
我正在制作一个应用程序,其中用户对来自一组公民对象的“公民”进行投票,并且该公民成为最佳公民。如果公民有3个或更多“投票”,则他们才有资格成为“最佳公民”。我在管理员中添加公民和投票,所以我们不会在这里处理。这些是我的模特:
best_app / models.py
from django.db import models
class Citizen(models.Model):
name = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
can_best = models.BooleanField(False)
def __unicode__(self):
return self.name
class Best_Citizen(models.Model):
name = models.CharField(max_length=200)
citizen = models.OneToOneField(Citizen)
def __unicode__(self):
return self.name
我在choose_best视图中遇到问题,选择的公民应该通过主键缩小。我不能在对象列表上调用get(),但在我看来,我应该做什么。我也尝试过滤缩小视图,语法不正确。
from best_app.models import Citizen, Best_Citizen
from django.shortcuts import render, get_object_or_404, get_list_or_404
def index(request):
citizens = Citizen.objects.all()
# citizens = get_list_or_404(Citizen)
for citizen in citizens:
if citizen.votes >= 3:
citizen.can_best = True
citizen.save()
return render(request, 'best_app/index.html', {'citizens':citizens})
def detail(request, citizen_id):
try:
citizen = Citizen.objects.get(pk=citizen_id)
except Citizen.DoesNotExist:
print "raise Http404"
return render(request, 'best_app/detail.html', {'citizen':citizen})
# return HttpResponse("You're looking at poll %s." % citizen.name)
def choose_best(request):
best_candidates = get_list_or_404(Citizen, can_best=True) # narrow down the candidates for best citizen to those with >= 3 votes
if request.method == 'POST':
try:
selected_choice = best_candidates.get(pk=request.POST['choice'])
except (KeyError, Citizen.DoesNotExist):
return render(request, 'index.html')
else:
Best_Citizen.objects.all().delete() # Current best citizen is deleted to make way for new best citizen
new_best = Best_Citizen(citizen=selected_choice)
new_best.save()
return render(request, 'best_app/index.html', {'new_best':new_best})
else:
return render(request, 'best_app/choose_best.html', {'best_candidates':best_candidates})
我收到错误消息“List属性没有属性获取”。如果过滤并且不起作用,我如何通过主键选择所选的“最佳候选人”? 谢谢!
答案 0 :(得分:0)
当documentation for get_list_or_404
状态时,它会将其结果转换为列表。如果你想进一步过滤它是不好的:所以不要使用那个快捷方式。
best_candidates = Citizen.objects.filter(can_best=True)