Скажем, у меня был кусок кода, как:Проверить QuerySet пусто в 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.
Где я буду неправильно?
EDIT:
Я изменил код, ссылающийся "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') и проверить количество вариантов, которые он содержит.
Как выглядит код модели «Вопрос»? –
См. Edit – Jon