The `SlugRelatedField` is a class in Django Rest Framework (DRF)...
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:
-
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.
-
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 aCategory
with aslug
value of"electronics"
, the field will serialize theCategory
as"electronics"
instead of itsid
(primary key). -
Deserialization: If you pass a category slug like
"electronics"
during deserialization, Django Rest Framework will look up the correspondingCategory
object using theslug
field and associate it with theProduct
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.