0
Django 1.6/Python 2.7。如何使用Django中的對象列表中的發佈數據調用對象?
我正在製作一個應用程序,用戶在一組公民對象上投票選擇「公民」,這個公民成爲最好的公民。一個公民只有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 attribute has no attribute get」。如何通過主鍵選擇所選的'最佳候選',如果過濾並且無法使用?
謝謝!
他也能做到這一點'selected_choice = get_object_or_404(西鐵城,PK = request.POST [ '選擇'])',而不是'selected_choice = best_candidates.get(PK = request.POST [ '選擇']) '(並保留get_list_or_404零件) – tfitzgerald
@Daniel Roseman 過濾器是我嘗試的第一件事,並且我一直以10爲基數得到錯誤'int()的無效字面值:''。進一步檢查後,這與selected_choice = best_candidates.get(pk = request.POST ['choice'])相關聯 –