3 - Class Based Views - Django REST Framework
3 - Class Based Views - Django REST Framework
class SnippetList(APIView):
"""
List all snippets, or create a new snippet.
"""
def get(self, request, format=None):
snippets = Snippet.objects.all()
serializer = SnippetSerializer(snippets, many=True)
return Response(serializer.data)
So far, so good. It looks pretty similar to the previous case, but we've got better separation between the
different HTTP methods. We'll also need to update the instance view in views.py .
class SnippetDetail(APIView):
"""
Retrieve, update or delete a snippet instance.
"""
def get_object(self, pk):
try:
return Snippet.objects.get(pk=pk)
except Snippet.DoesNotExist:
raise Http404
That's looking good. Again, it's still pretty similar to the function based view right now.
We'll also need to refactor our snippets/urls.py slightly now that we're using class-based views.
urlpatterns = [
path('snippets/', views.SnippetList.as_view()),
path('snippets/<int:pk>/', views.SnippetDetail.as_view()),
]
urlpatterns = format_suffix_patterns(urlpatterns)
Okay, we're done. If you run the development server everything should be working just as before.
Using mixins
One of the big wins of using class-based views is that it allows us to easily compose reusable bits of
behavior.
The create/retrieve/update/delete operations that we've been using so far are going to be pretty similar for
any model-backed API views we create. Those bits of common behavior are implemented in REST
framework's mixin classes.
Let's take a look at how we can compose the views by using the mixin classes. Here's our views.py module
again.
class SnippetList(mixins.ListModelMixin,
mixins.CreateModelMixin,
generics.GenericAPIView):
queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
We'll take a moment to examine exactly what's happening here. We're building our view using
GenericAPIView , and adding in ListModelMixin and CreateModelMixin .
The base class provides the core functionality, and the mixin classes provide the .list() and .create()
actions. We're then explicitly binding the get and post methods to the appropriate actions. Simple enough
stuff so far.
class SnippetDetail(mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
generics.GenericAPIView):
queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
class SnippetList(generics.ListCreateAPIView):
queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
class SnippetDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
Wow, that's pretty concise. We've gotten a huge amount for free, and our code looks like good, clean,
idiomatic Django.
Next we'll move onto part 4 of the tutorial, where we'll take a look at how we can deal with authentication and
permissions for our API.