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.
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.
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
:
Python1# project/myapp/views.py 2from rest_framework import generics 3from .models import Todo 4from .serializers import TodoSerializer 5 6class TodoDetail(generics.RetrieveAPIView): 7 queryset = Todo.objects.all() 8 serializer_class = TodoSerializer
In this code:
- We import
RetrieveAPIView
fromgenerics
, which provides theget
method handler to retrieve a model instance. - We define
TodoDetail
as a class-based view inheriting fromRetrieveAPIView
. - We set the
queryset
to fetch allTodo
objects. - We set the
serializer_class
toTodoSerializer
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.
Next, we need to map a URL to our new TodoDetail
view so that we can access it via an HTTP GET request. In this case, our view is designed to handle retrieving one specific object from the database. Because of this, we need to specify the required object's id in the request.
Here's how to add the URL configuration in urls.py
:
Python1# project/myapp/urls.py 2from django.urls import path 3from .views import TodoDetail 4 5urlpatterns = [ 6 path('todos/<int:pk>/', TodoDetail.as_view(), name='todo_detail'), 7]
In this code:
- We import the
path
function and ourTodoDetail
view. - We add a new URL pattern
todos/<int:pk>/
, wherepk
is a placeholder for the primary key of the Todo item, which is the object's id. The variable type<int>
indicates that it is an integer, which is optional and by default a string.pk
is a variable name and can be anything, not necessarilypk
. - We map this pattern to the
TodoDetail
view usingas_view()
and give it the nametodo_detail
.
The endpoint is /api/todos/<id>
. For example, if we want to retrieve an item with id 13
, we can do it with /api/todos/13
.
To test our new endpoint, let's use a simple Python script to create a To-Do item and retrieve it.
Here's a sample script send_request.py
to test this functionality:
Python1# send_request.py 2import requests 3 4URL = 'http://0.0.0.0:3000/api/todos/' 5 6# Create a new To-Do item to ensure the database is not empty 7new_todo = {'task': 'Learn Django'} 8post_response = requests.post(URL, json=new_todo) 9print(post_response.json()) # Expect to see the newly created TODO item 10 11# Retrieve the newly created To-Do item 12todo_id = post_response.json()['id'] # Getting id of the item we just created 13retrieve_url = f'http://0.0.0.0:3000/api/todos/{todo_id}/' # Plugging the id into url 14get_response = requests.get(retrieve_url) 15print(get_response.json()) # Expect to see the details of the TODO item with created ID
In this code:
- We first define the base URL for our To-Do items API.
- We create a new To-Do item with the task
Learn Django
using a POST request. - We print the response to verify the item creation.
- We extract the
id
of this new To-Do item from the response. - We construct a retrieval URL using this
id
and make a GET request to fetch the specific To-Do item. - We print the response to verify the retrieval.
Expected output:
JSON1# Output after post request 2{'id': 1, 'task': 'Learn Django'} 3 4# Output after get request 5{'id': 1, 'task': 'Learn Django'}
Retrieving a specific To-Do item can be particularly useful in several scenarios within our To-Do application:
-
Viewing Details of a To-Do Item: Users may want to see the complete details of a specific To-Do item, such as the task description, due date, and any additional notes. By retrieving a single item, we can display this detailed information on a separate page or modal.
-
Editing a To-Do Item: When users decide to edit a To-Do item, we first need to fetch the current data of that item to prepopulate the edit form. This allows users to see the existing values and make necessary changes.
-
Marking a To-Do Item as Complete: If we have a feature that allows users to mark items as complete, we need a quick way to fetch the specific To-Do item to update its status. This improves the user experience by providing immediate feedback on their actions.
-
Deleting a To-Do Item: Before deleting a To-Do item, we might want to display a confirmation dialog with the item's details to ensure that users are aware of what they are about to delete. This can help prevent accidental deletions.
By implementing the retrieval of individual To-Do items, we can make our application more interactive and user-friendly, providing a better overall experience for the end-users.
In this lesson, we covered retrieving individual To-Do items using Django REST Framework. We:
- Created a
TodoDetail
view usingRetrieveAPIView
. - Configured the URL routing for item retrieval.
- Tested our endpoint using a Python script.
Make sure to try out the practice exercises that follow this lesson to reinforce your understanding. In the next lesson, we will focus on another CRUD operation to further enhance our To-Do API.
Keep practicing, and excellent work so far! Your journey in mastering CRUD operations continues.