SBA - 장고 3.1

장고 3.1

SBA - 장고 3.1 장고 3.1
본 토픽은 현재 준비중입니다. 공동공부에 참여하시면 완성 되었을 때 알려드립니다.

A shortcut: get_object_or_404()

404 예외에 대한 단축 기능 제공

만약 객체가 존재하지 않을 때 get() 을 사용하여 Http404 예외를 발생시키는것은 자주 쓰이는 용법입니다. Django에서 이 기능에 대한 단축 기능을 제공합니다. detail() 뷰를 단축 기능으로 작성하면 다음과 같습니다.

It’s a very common idiom to use get() and raise Http404 if the object doesn’t exist. Django provides a shortcut. Here’s the detail() view, rewritten:

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)
    question = get_list_or_404(Question, pk=question_id)
    return render(request, 'polls/detail.html', {'question': question})

쇼컷을 이용한 404 페이지 

get_object_or_404() 함수는 Django 모델을 첫번째 인자로 받고, 몇개의 키워드 인수를 모델 관리자의 get() 함수에 넘깁니다. 만약 객체가 존재하지 않을 경우, Http404 예외가 발생합니다.

The get_object_or_404() function takes a Django model as its first argument and an arbitrary number of keyword arguments, which it passes to the get() function of the model’s manager. It raises Http404 if the object doesn’t exist.

https://docs.djangoproject.com/ko/3.1/topics/http/shortcuts/#django.shortcuts.get_list_or_404

철학

상위 계층에서 ObjectDoesNotExist 예외를 자동으로 잡아 내는 대신 get_object_or_404() 도움 함수(helper functoin)를 사용하거나, ObjectDoesNotExist 예외를 사용하는 대신 Http404 를 사용하는 이유는 무엇일까요?

왜냐하면, 모델 계층을 뷰 계층에 연결하는 방법이기 때문입니다. Django의 중요한 설계 목표는, 약결합(loos처e coupling)을 관리하는 데에 있습니다. 일부 제어된 결합이 django.shortcuts 모듈에서 도입되었습니다

또한, get_object_or_404() 함수처럼 동작하는 get_list_or_404() 함수가 있습니다. get() 대신 filter()

댓글

댓글 본문
버전 관리
happydeveloper
현재 버전
선택 버전
graphittie 자세히 보기
  • 토픽 0
  • 모듈 0
  • 코스 0
  • 봤어요 0
  • 댓글 0
  • 명예의 전당 0