在没有选择发布的情况下防止民意调查

时间:2014-11-09 04:42:04

标签: python django django-models

我一直在Django tutorial工作,我在第5部分,它要求我创建一个测试,看看是否有没有选择的民意调查。对于我们所做的每一项其他测试,例如确保过去(而不是未来)的民意调查都已发布,我们只需创建两个民意调查:一个过去有一个pub_date,另一个过去有一个:

def test_index_view_with_future_poll_and_past_poll(self):
        """
        Even if both past and future polls exist, only past polls should be
        displayed.
        """

        create_poll(question='past poll', days=-30)
        create_poll(question='future poll', days=30)
        response = self.client.get(reverse('polls:index'))
        self.assertQuerysetEqual(
            response.context['latest_poll_list'],
            ['<Poll: past poll>'])

对于相应的视图,我们只需添加以下函数:

def get_queryset(self):
    """Return the last five published poll."""
    #Returns polls published at a date the same as now or before
    return Poll.objects.filter(pub_date__lte=timezone.now()).order_by('pub_date')[:5]

它只是使用filter()函数在将来过滤掉pub_date的任何民意调查,这很简单。但我似乎无法做出相同的民意调查,没有任何选择,这是我迄今为止的测试功能:

class PollsAndChoices(TestCase):
    """ A poll without choices should not be displayed
    """
    def test_poll_without_choices(self):
        #first make an empty poll to use as a test
        empty_poll = create_poll(question='Empty poll', days=-1)
        poll = create_poll(question='Full poll',days=-1)
        full_poll = poll.choice_set.create(choice_text='Why yes it is!', votes=0)
        #create a response object to simulate someone using the site
        response = self.client.get(reverse('polls:index'))
        self.assertQuerysetEqual(response.context['latest_poll_list'], ['<Poll: Full poll>'])

这就是我对相关观点的看法:

class IndexView(generic.ListView):
    #We tell ListView to use our specific template instead of the default just like the rest
    template_name = 'polls/index.html'
    #We use this variable because the default variable for Django is poll_list
    context_object_name = 'latest_poll_list'

    def get_queryset(self):
        """Return the last five published poll."""
        #Returns polls published at a date the same as now or before
       return Poll.objects.filter(pub_date__lte=timezone.now()).order_by('pub_date')[:5]

    def show_polls_with_choices(self):
       """ Only publish polls that have choices """
       #Since choice_set displays a list we can use it to make sure a poll with an empty list
       #is not published
        for poll in Poll.objects.all():
            if poll.choice_set.all() is not []:
                return poll

基本上没有任何事情发生,测试失败了:

Traceback (most recent call last):
  File "C:\Users\ELITEBOOK\dropbox\programming\mysite\polls\tests.py", line 125, in    test_poll_without_choices
    self.assertQuerysetEqual(response.context['latest_poll_list'], ['<Poll: Full poll>'])
  File "C:\Users\Elitebook\Dropbox\Programming\virtualenvs\project\lib\site-  packages\django\test\testcases.py", line 829
, in assertQuerysetEqual
    return self.assertEqual(list(items), values)
AssertionError: Lists differ: ['<Poll: Empty poll>', '<Poll:... != ['<Poll: Full poll>']

First differing element 0:
<Poll: Empty poll>
<Poll: Full poll>

First list contains 1 additional elements.
First extra element 1:
<Poll: Full poll>

- ['<Poll: Empty poll>', '<Poll: Full poll>']
+ ['<Poll: Full poll>']

所以应用程序仍在发布空轮询和完整轮询,有没有办法使用filter()方法根据是否有选择来优化民意调查?

2 个答案:

答案 0 :(得分:1)

def show_polls_with_choices(self):    
    return Poll.objects.exlude(choice_set__isnull=True)


def get_queryset(self):
    """Return the last five published NOT EMPTY polls."""
    #Returns polls published at a date the same as now or before
    return self.show_polls_with_choices().filter(pub_date__lte=timezone.now()).order_by('pub_date')[:5]

答案 1 :(得分:1)

class IndexView(generic.ListView):
template_name = 'polls/index.html'
context_object_name = 'latest_question_list'

def get_queryset(self):
    return Polls.objects.exclude(choice__isnull=True).filter(pub_date__lte=timezone.now()).order_by('-pub_date')[:10]

这可能是解决问题的最简单方法,因为它结合了两者;你的函数和视图工作所必需的get_queryset

如果它用于IndexView,您需要在索引视图中运行的测试中创建至少一个选项