【发布时间】:2014-09-26 11:34:33
【问题描述】:
假设我有一段代码,例如:
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”对象没有“过滤器”属性
这是从它提到的Django tutorial的最底部获取的
例如,可以在没有选择的网站上发布问题是很愚蠢的。因此,我们的观点可以检查这一点,并排除此类问题。
我哪里错了?
编辑:
我将引用“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
为 cms_mgr 编辑
基本上我想检查与指定问题相关的选项数是否为空。当我转到此链接时 - http://127.0.0.1:8000/polls/3/ 我想从 id ('3') 中获取问题并检查它包含的选项数量。
【问题讨论】:
-
Question型号代码是什么样的?