【NB】快捷方式: get_object_or_404()
http://cdn.u1.huluxia.com/g4/M01/E4/10/rBAAdmNt5TiAI7GyAADQ4EfoNCk476.jpg
如果对象不存在的一个非常习惯用法使用get()并引发HTTP404错误。 Django提供了一个捷径。下面是 detail() 视图,polls/views.py 改写:
from django.shortcuts import get_object_or_404, render
from .models import Question
# ...
def detail(request, question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request, 'polls/detail.html', {'question': question})http://cdn.u1.huluxia.com/g4/M01/E4/10/rBAAdmNt5TmAa2kOAAG3b70_RB0601.jpg
get_object_or_404()函数接受一个Django模型作为第一个参数和关键字任意参数数量,它传递到模型管理的 get()函数。
如果对象不存在将引发HTTP404。
还有一个get_list_or_404()函数,它的工作原理就像get_object_or_404()- 除了使用 filter()而不是get()方法。如果列表是空的它会引起HTTP404。
页:
[1]