DetailView on Django REST – multiple methods

Long time since I wrote something on Django, but today it surprised me again with its flexibility. Let me put it down here. Remember the traditional DetailView ?

Example from: https://docs.djangoproject.com/en/1.10/ref/class-based-views/generic-display/#detailview

from django.views.generic.detail import DetailView
from articles.models import Article<img src="blob:https://wordpress.com/64cb7829-8030-43aa-91de-8e4cf958aad0" alt="Selection_407.png" class="alignnone size-full wp-image-media-2"/>

class ArticleDetailView(DetailView):

    model = Article

    def get_object(self): 
        try: 
            return Article.objects.get(pk=self.kwargs.get('pk'))

Setting this thing up in Angular to retrieve details of an Article, I used to follow something similar:

from articles.models import Article
from django.http import Http404

class ArticleDetailView(generics.RetrieveAPIView):

    model = Article
    serializer_class = ArticleDetailsSerializer
    queryset = Article.objects.all() 

    def get_object(self): 
        try: 
            return Article.objects.get(pk=self.kwargs.get('pk'))
        expect ValueError:
            return Http404

I was looking through the documentation agian , and I see that the entire thing can be done in like 3 lines. Take a look:

from articles.models import Article

class ArticleDetailView(generics.RetrieveAPIView):

    model = Article
    serializer_class = ArticleDetailsSerializer
    queryset = Article.objects.all() 

Note: This should work only if you have Article primary key received on urls.py as pk. ie, something like this in your urls.py:

from django.conf.urls import url

from article.views import ArticleDetailView

urlpatterns = [
    url(r'^article/(?P<pk>[\w]+)/$', ArticleDetailView.as_view(), name='article-list'),
]

In case you do not want to send in the primary key, you can provide the custom slug name using the attribute lookup_fields in your view definition. Read more here: http://www.django-rest-framework.org/api-guide/generic-views/#attributes

An example request to the URL would be http://127.0.0.1:8000/article/50. Django for life, Enjoy humans.