Day 10 (week 2) — ViewSets in Django

ViewSets in Django are almost the same thing as Views except they provide operations like read or update instead of get and put. What this is going to allow us to do is refactor the views in our API to be much simpler. To do this, we are also going to need a Router class which will handle wiring up the URL conf for us.

I won’t include the same code from yesterday, since it’s the same project. Here is the refactored version, which is much cleaner.

class SnippetViewSet(viewsets.ModelViewSet):
This viewset automatically provides `list`, `create`, `retrieve`,
`update` and `destroy` actions.
Additionally we also provide an extra `highlight` action.
queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly,
def highlight(self, request, *args, **kwargs):
snippet = self.get_object()
return Response(snippet.highlighted)
def perform_create(self, serializer):
class UserViewSet(viewsets.ReadOnlyModelViewSet):
This viewset automatically provides `list` and `detail` actions.
queryset = User.objects.all()
serializer_class = UserSerializer

Notice now that we have only two classes: one for Snippets and the other for Users. The ViewSet that both classes inherit from bring along all the functionality that we need for our API.

This is another great example of how knowing which piece of high-level code to run is critical in using a framework like the Django REST framework. Ordinarily, we would have to write out all the database interaction code along with all the different API endpoints. Once we understand how the framework works, and what code we get for free as a result of using framework calls, the amount of code we have to write is greatly reduced.

I didn’t do much else with Django or Ember today. It was kind of a strange day that started out with me reading a big chunk of Ryan Holiday’s new book called Perennial Seller. Just a little re-ordering of my day, since I normally read in the afternoons/evenings. Perhaps I should have just stuck to my normal routine instead of mixing it up.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.