2015-10-10 42 views
1

我認爲我的查詢集正在返回一個空列表而不是「不存在的錯誤」。我希望它返回一個錯誤,以便我可以返回一個替代消息。 HTML正在返回一個空的子彈點而不是所需的消息。查詢集返回空列表而不是錯誤

view.py

def results(request, foo_id): 

    template_name = 'results.html' 
    foo = Foo.objects.get(id=foo_id) 
    foo_id = foo_id 
    try:  
     foobars = FooBar.objects.filter(foo__foo=foo.foo) 

     return render(request, template_name, {'foobars': foobars, 
      'zipcode':zipcode, 'foo_id':foo_id}) 

    except FooBar.DoesNotExist: 
     message = 'Sorry there are no FooBar with that foo' 
     return render(request, template_name, {'message':message, 
      'foo_id':foo_id}) 

models.py

class Foo(models.Model): 
    foo = models.IntegerField(null=True) 

class FooBar(models.Model): 
    foo = models.ForeignKey('Foo') 
    title = models.CharField(max_length=100) 
    description = models.CharField(max_length=400, null=False, blank=True) 


    def __str__(self): 
     return self.title 

results.html

<html> 

<h2>Title</h2> 

<ul id='id_results'> 
    {% for foobar in foobars%} 
     <li>{{ foobar.name }}</li> 
    {% empty %} 
     <li> {{ message }} </li> 
    {% endfor %} 
</ul> 

<a href= "/new_foobar/">New FooBar </a> 

回答

1

.filter()沒有引發excepti如果對象在查詢集中不存在,則返回空列表[]

我們本來可以在查詢集上使用.get(),在沒有對象存在的情況下引發這個異常。但是,我們將無法使用它,因爲查詢集中可能有多個對象符合條件,並且在返回多個對象的情況下,會引發異常。

get()引發MultipleObjectsReturned如果不止一個對象被 發現。

您可以改爲使用foobars的布爾值來檢查,如果它是空列表,則顯示該消息。

def results(request, foo_id): 

    template_name = 'results.html' 
    foo = Foo.objects.get(id=foo_id) 
    foo_id = foo_id 

    foobars = FooBar.objects.filter(foo__foo=foo.foo) 
    if foobars: # check if there are any matching objects  
     return render(request, template_name, {'foobars': foobars, 
      'zipcode':zipcode, 'foo_id':foo_id}) 
    else: # no matching objects 
     message = 'Sorry there are no FooBar with that foo' # display the message 
     return render(request, template_name, {'message':message, 
      'foo_id':foo_id})