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:
In this code:
- We import
RetrieveAPIViewfromgenerics, which provides thegetmethod handler to retrieve a model instance. - We define
TodoDetailas a class-based view inheriting fromRetrieveAPIView. - We set the
querysetto fetch allTodoobjects. - We set the
serializer_classtoTodoSerializerto 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.
