← All Articles

2021.02.12 (금)

Posted on

예외처리

  • Http404 사용
from django.http import Http404
def detail(request, question_id):
    try:
        question = Question.objects.get(pk=question_id)
    except Question.DoesNotExist:
        raise Http404("Question does not exist")
  • getobjector_404() 사용
from django.shortcuts import get_object_or_404, render
def detail(request, question_id):
    question = get_object_or_404(Question, pk=question_id)

getobjector404() 함수처럼 동작하는 getlistor404() 함수가 있습니다. get() 대신 filter() 를 쓴다는 것이 다릅니다. 리스트가 비어있을 경우, Http404 예외를 발생시킵니다.

database 변경 관련 (모델이 수정된 경우)

https://yuda.dev/216