The `SlugRelatedField` is a class in Django Rest Framework (DRF)...

June 30, 2025 at 10:22 AM

SlugRelatedField

The SlugRelatedField is a class in Django Rest Framework (DRF) that is used as a serializer field to represent relationships using a slug field on the related model. It is typically used when you want to serialize and deserialize relationships using a human-readable unique field (like a slug) instead of the primary key of the related model.

Here’s what it does:

  1. Serialization: When serializing, it represents a relationship using the value of the specified slug field on the related model rather than using the primary key.

  2. Deserialization: When deserializing, it converts the provided slug back into a related model instance by looking it up based on the specified slug field.

Example Usage

Assume the following models:

from django.db import models

class Category(models.Model):
    name = models.CharField(max_length=100)
    slug = models.SlugField()

class Product(models.Model):
    name = models.CharField(max_length=100)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)

Now, when creating a serializer for the Product model:

from rest_framework import serializers

class ProductSerializer(serializers.ModelSerializer):
    category = serializers.SlugRelatedField(
        queryset=Category.objects.all(),  # Queryset to look up the related object
        slug_field='slug'  # Field to use for the relationship
    )

    class Meta:
        model = Product
        fields = ['name', 'category']

What This Does:

  • Serialization: If a Product object has a Category with a slug value of "electronics", the field will serialize the Category as "electronics" instead of its id (primary key).

  • Deserialization: If you pass a category slug like "electronics" during deserialization, Django Rest Framework will look up the corresponding Category object using the slug field and associate it with the Product instance.

Note:

  • The queryset parameter is mandatory because it is used to look up the related object during deserialization.
  • The slug_field parameter specifies the name of the field on the related model to be used as the slug. This field must be unique in the related model.

This is useful when you want APIs to work with more user-friendly identifiers like slugs instead of raw database IDs.

Generate your own explanations
Download our vscode extension
Read other generated explanations

Built by @thebuilderjr
Sponsored by beam analytics
Read our terms and privacy policy
Forked from openai-quickstart-node