我有一个简单的模板标签,它返回一个随机事实。当数据库中没有事实时,我得到的异常值列表索引超出范围。我用 try包装了查询集,但* 除外,还检查模板中是否有事实。您可以看到以下代码:
fact.py
# template tag
from django import template
from facts.models import Fact
register = template.Library()
def random_fact():
try:
fact = Fact.objects.order_by('?')[0]
except Fact.DoesNotExist:
fact = None
return {'fact': fact}
register.inclusion_tag('facts/fact.html')(random_fact)
fact.html
<!-- Random Fact Start -->
<div class="panel panel-default sidebar">
<div class="panel-heading">
<h3 class="panel-title">Did you know?</h3>
</div>
<div class="panel-body">
{% if fact %}
<p class="text-left">{{ fact.fact }}</p>
<p class="text-right"><i class="fa fa-link"></i> <i><a href="{{ fact.website }}" target="_blank">{{ fact.author }}</a></i></p>
{% else %}
<p class="text-left">There are currently no studying tips!</p>
{% endif %}
</div>
</div>
<!-- Random Fact End -->
答案 0 :(得分:3)
试试这个:
def random_fact():
fact = Fact.objects.order_by('?').first()
return {'fact': fact}
答案 1 :(得分:1)
Fact.objects.order_by('?')
表达式不会抛出DoesNotExist
- 它将变为空列表。获取空列表中的第0项会抛出IndexError
,抓住它:
def random_fact():
try:
fact = Fact.objects.order_by('?')[0]
except IndexError:
fact = None