環境
- Django 3.0.3
オブジェクト1件を取得
オブジェクトを1件取得もしくは、オブジェクトが見つからなかったら404を表示させるにはget_object_or_404
を使います。
get_object_or_404(klass, *args, **kwargs)
Django のショートカット関数 | Django ドキュメント | Django
from django.shortcuts import get_object_or_404
from apps.products.models Product
class ProductView(LoginRequiredMixin, generic.TemplateView):
""" 商品詳細ページ """
model = Product
template_name = 'products/detail.html'
raise_exception = True # 403ページの表示
pk_url_kwarg = "prroduct_id"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['product'] = get_object_or_404(
Product,
pk=self.kwargs['product_id']
)
return context
複数条件で取得
取得条件が複数ある場合はこのように条件を複数指定することもできます。
filter
を使う必要はありません。
from django.shortcuts import get_object_or_404
from apps.products.models Product
class ProductView(LoginRequiredMixin, generic.TemplateView):
""" 商品詳細ページ """
model = Product
template_name = 'products/detail.html'
raise_exception = True # 403ページの表示
pk_url_kwarg = "prroduct_id"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['product'] = get_object_or_404(
Product,
pk=self.kwargs['product_id'],
price=10000,
title='商品名'
)
return context
オブジェクト複数件を取得
オブジェクトを複数件を取得するにはget_list_or_404
を使います。
オブジェクトが見つからなかったら404を表示します。
get_list_or_404(klass, *args, **kwargs)
Django のショートカット関数 | Django ドキュメント | Django
from django.shortcuts import get_object_or_404
from apps.products.models Product
class ProductsView(LoginRequiredMixin, generic.TemplateView):
""" 商品リストページ """
model = Product
template_name = 'products/index.html'
raise_exception = True # 403ページの表示
pk_url_kwarg = "prroduct_id"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['products'] = get_list_or_404(
Product,
price=10000,
)
return context
複数条件で取得
取得条件が複数ある場合はこのように条件を複数指定することもできます。
get_list_or_404
の場合もfilter
を使う必要はありません。
from django.shortcuts import get_list_or_404
from apps.products.models Product
class ProductsView(LoginRequiredMixin, generic.TemplateView):
""" 商品リストページ """
model = Product
template_name = 'products/index.html'
raise_exception = True # 403ページの表示
pk_url_kwarg = "prroduct_id"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['products'] = get_list_or_404(
Product,
price=10000,
title='商品名'
)
return context
まとめ
get_object_or_404
はオブジェクトを1件取得。見つからなかった場合は404を表示。複数条件で検索可能。
get_list_or_404
オブジェクトを複数取得。見つからなかった場合は404を表示。複数条件で検索可能。