Last modified: Jan 10, 2023 By Alexander Williams

How to Access a Queryset in Django DetailView

Django provides us the get_context_data method that helps to access Querysets in Generic display views.

Let's see how t use the get_context_data method with Detailview.

views.py:


class ArticleDetailView(DetailView):

    model = Topic
    template_name = "Detail.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        #Queryset
        context['my_queryset'] = Topic.objects.all()
        return context

urls.py:


urlpatterns = [
    .
    path('article/<slug:pk>/', ArticleDetailView.as_view()),
    .
]

Detail.html:


<html>
   <head>
   </head>
   <body>


{{my_queryset}}


 </body>
</html>

http://127.0.0.1:8000/article/1/:

How to Access a Queryset in Django DetailView