モデルQuestionは
from django.db import models class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published')
viewのコードは
from django.http import Http404 from django.shortcuts import render from .models import Question # ... def detail(request, question_id): try: question = Question.objects.get(pk=question_id) except Question.DoesNotExist: raise Http404("Question does not exist") return render(request, 'polls/detail.html', {'question': question})
上記viewをショートカット: get_object_or_404()で書き直したもの
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})
上記コードの解説文
設計思想
なぜ ObjectDoesNotExist 例外を高水準で自動的にキャッチせず、ヘルパー関数 get_object_or_404() を使うのでしょうか、また、なぜモデル API に ObjectDoesNotExist ではなく、 Http404 を送出させるのでしょうか?
答えは、モデルレイヤとビューレイヤをカップリングしてしまうからです。 Django の最も大きな目標の一つは、ルーズカップリングの維持にあります。いくつかの制御カップリングは、 django.shortcuts モジュールの中にあります。
自分なりの解釈
設計思想の中のレイヤとはモデルレイヤはmodelの領分、ビューレイヤはviewの領分のことで、上記ショートカットの中でオブジェクトが無い時は404を送出するという二つのこと(カップリング)と言う意味でよろしいのでしょうか。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/09/26 07:38