Retrieving To-Dos

Introduction

Welcome back! In the previous lesson, we introduced CRUD operations focusing on creating To-Do items using the Django REST framework. We went through the setup of views and serializers for adding To-Dos, configured URLs, and tested our API.

In this lesson, we will focus on another essential part of CRUD operations: retrieving individual To-Do items. Imagine we have a To-Do app running, and we want to show users details of To-Dos when they click on them. To do it, we need to be able to retrieve information of a specific To-Do item. By the end of this lesson, you will be able to implement an endpoint that exactly this and understand how to test this retrieval.

Simplified ToDo Model

For this lesson, we will be using our base version of our ToDo model with just the fields task and completed. While we added more fields in the previous unit, we will revert to this simpler model for brevity. However, the contents of this unit are perfectly compatible with the extended variant of the model.

Creating the TodoDetail View

Let's move on to creating the view that will help us retrieve individual To-Do items. We'll use Django REST Framework's RetrieveAPIView for this purpose.

Here is how you can implement the TodoDetail class in views.py:

Python
# project/myapp/views.py
from rest_framework import generics
from .models import Todo
from .serializers import TodoSerializer

class TodoDetail(generics.RetrieveAPIView):
    queryset = Todo.objects.all()
    serializer_class = TodoSerializer

In this code:

  • We import RetrieveAPIView from generics, which provides the get method handler to retrieve a model instance.
  • We define TodoDetail as a class-based view inheriting from RetrieveAPIView.
  • We set the queryset to fetch all Todo objects.
  • We set the serializer_class to TodoSerializer to ensure our data is converted to/from JSON correctly.

We define queryset as Todo.objects.all because RetrieveAPIView will automatically filter this queryset based on the primary key provided in the URL to retrieve just one item. The queryset specifies the initial set of all possible objects from which a single object will be retrieved.

As you can see, creating new views is extremely easy with pre-defined Django generics. However, some details are vital to understand. Let's examine them.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal