Member-only story

What is @action decorator in Django Rest Framework?

Gokul nath
4 min readSep 7, 2024

--

Non members can click here to read the story.

Let’s explore about the usage of action decorator in Django Rest framework.

Before we proceed, I assume you have basic understanding of Django and Django rest framework.

Blog Application

Let’s create a basic REST API for Blog application to understand the usage of action decorator.

models.py

A blog can have a title, description and is_active fields.

from django.db import models


class Blog(models.Model):
name = models.CharField(max_length=100)
content = models.TextField()
is_active = models.BooleanField(default=True)


def __str__(self) -> str:
return f"{self.name}"

class Meta:
db_table = "blog"

serializers.py

Let’s keep the serializer’s definition to be same as models.py, hence I’m using ModelSerializer. This can be imported from rest_framework.serializers

from rest_framework import serializers
from blog.models import Blog

class BlogSerializer(serializers.ModelSerializer):

class Meta:
model = Blog
fields = "__all__"

views.py

Let create a endpoints for CRUD operations on blog model with viewsets.

I’m using viewsets…

--

--

Gokul nath
Gokul nath

Written by Gokul nath

Backend developer | Python | Django | Nest JS

No responses yet