Using generic class-based views

Using the mixin classes we've rewritten the views to use slightly less code than before, but we can go one step further. REST framework provides a set of already mixed-in generic views that we can use to trim down our views.py module even more.

  1. from snippets.models import Snippet
  2. from snippets.serializers import SnippetSerializer
  3. from rest_framework import generics
  4. class SnippetList(generics.ListCreateAPIView):
  5. queryset = Snippet.objects.all()
  6. serializer_class = SnippetSerializer
  7. class SnippetDetail(generics.RetrieveUpdateDestroyAPIView):
  8. queryset = Snippet.objects.all()
  9. 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.