說我有過一段代碼:檢查查詢集是在Django
class DetailView(generic.DetailView):
model = Question
template_name = 'polls/detail.html'
def get_queryset(self):
"""
Excludes any questions that aren't published yet.
"""
all_entries = Choice.objects.all()
if not all_entries:
return Question.objects.filter(pub_date__lte=timezone.now())
我試圖讓所有從一個問題的選擇,並返回404,如果沒有符合條件。但是我只設法實現它的一部分,並得到了錯誤:
'NoneType' object has no attribute 'filter'
這是從Django tutorial的最底部它提到
For example, it’s silly that Questions can be published on the site that have no Choices. So, our views could check for this, and exclude such Questions.
我要去哪裏錯了多久?
編輯:
我改變了代碼引用 「all_entries」 有:
all_entries = Choice.objects.all().count()
if all_entries > 0:
return Question.objects.filter(pub_date__lte=timezone.now())
但只是返回所有的問題,他們是否有選擇或不...
Models.py
from django.db import models
import datetime
from django.utils import timezone
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __str__(self): # __unicode__ on Python 2
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)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __str__(self): # __unicode__ on Python 2
return self.choice_text
EDIT對於cms_mgr
基本上我想檢查與指定問題相關聯的選擇是空號。當我去這個鏈接 - http://127.0.0.1:8000/polls/3/
我想從id('3')得到問題並檢查它包含的選項的數量。
什麼是'問題'模型代碼的樣子? – 2014-09-26 12:08:36
請參閱編輯 – Jon 2014-09-26 12:12:53