Django try block best use
У меня есть представление, которое принимает 2 аргумента :course_slug и chapter_slug и я хочу проверить, существуют ли заданные курс и глава в базе данных, так что какой лучший способ сделать это :
def Chapter_Detail(request,course_slug,chapter_slug):
try:
course = Course.objects.get(slug=course_slug)
except Course.DoesNotExist:
raise Http404("course does not exist")
try:
chapter = Chapter.objects.get(slug=chapter_slug)
except Chapter.DoesNotExist:
raise Http404("chapter does not exist")
'''
continue view logic
'''
context = {
'chapter':chapter,
'course' :course,
}
return render(request,'courses/chapter-detail.html',context)
или:
def Chapter_Detail(request,course_slug,chapter_slug):
try:
course = Course.objects.get(slug=course_slug)
chapter = Chapter.objects.get(slug=chapter_slug)
'''
continue view logic
'''
except Course.DoesNotExist:
raise Http404("course does not exist")
except Chapter.DoesNotExist:
raise Http404("chapter does not exist")
context = {
'chapter':chapter,
'course' :course,
}
return render(request,'courses/chapter-detail.html',context)
или:
def Chapter_Detail(request,course_slug,chapter_slug):
try:
course = Course.objects.get(slug=course_slug)
chapter = Chapter.objects.get(slug=chapter_slug)
except Course.DoesNotExist:
raise Http404("course does not exist")
except Chapter.DoesNotExist:
raise Http404("chapter does not exist")
else :
'''
continue view logic
'''
context = {
'chapter':chapter,
'course' :course,
}
return render(request,'courses/chapter-detail.html',context)
или есть лучший способ
логика представления означает, что мы собираемся работать с объектами курса и главы
Как упомянул Айден, вы можете использовать ярлык, специально созданный для этого.
from django.shortcuts import get_object_or_404
def Chapter_Detail(request,course_slug,chapter_slug):
course = get_object_or_404(Course, slug=course_slug)
chapter = get_object_or_404(Chapter, slug=chapter_slug)
'''
continue view logic
'''
context = {
'chapter':chapter,
'course' :course,
}
return render(request,'courses/chapter-detail.html',context)
Ваши три варианта также, конечно, будут работать. Блок else в третьем примере строго не нужен, так как либо будет ошибка raised, либо код будет продолжен.