Introduction

Welcome to the final lesson in this course. In this session, we will focus on defining custom methods for views in Django. Customizing views allows you to meet specific requirements for your API endpoints, improving the flexibility and functionality of your application.

Our objective in this lesson is to define a custom GET method for the TodoListCreate view. By the end of this lesson, you'll understand how to create a custom GET method, format the returned data, and test the custom method effectively.

Recap of the Setup

Before diving into the code, let's briefly recap what we've set up so far in prior lessons. We've created models, serializers, views, and URLs for a simple Todo application.

Here’s a code block that encapsulates our existing setup:

# models.py
from django.db import models

class Tag(models.Model):
    name = models.CharField(max_length=255)

class Todo(models.Model):
    task = models.CharField(max_length=255)
    completed = models.BooleanField(default=False)
    priority = models.IntegerField()
    assignee = models.CharField(max_length=255, blank=True, null=True)
    group = models.CharField(max_length=255, blank=True, null=True)
    tags = models.ManyToManyField(Tag, blank=True)

# serializers.py
from rest_framework import serializers
from .models import Todo, Tag

class TagSerializer(serializers.ModelSerializer):
    class Meta:
        model = Tag
        fields = ['id', 'name']

class TodoSerializer(serializers.ModelSerializer):
    tags = TagSerializer(many=True)

    class Meta:
        model = Todo
        fields = '__all__'

# views.py
from rest_framework import generics
from .models import Todo
from .serializers import TodoSerializer

class TodoListCreate(generics.ListCreateAPIView):
    queryset = Todo.objects.all()
    serializer_class = TodoSerializer

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

# urls.py
from django.urls import path
from .views import TodoListCreate, TodoDetail

urlpatterns = [
    path('todos/', TodoListCreate.as_view(), name='todo_list_create'),
    path('todos/<int:pk>/', TodoDetail.as_view(), name='todo_detail'),
]

This code sets up our Todo and Tag models and connects them with corresponding serializers and views. Note that we omit the Group model, priority model, and TagGroup model for brevity in this lesson, but they would be completely compatible with the materials of this lesson.

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