Vishesh Mehta
Vishesh Mehta

Reputation: 79

Slug Field in Django Rest Framework

I have a model class that has a Title field. Now I want to generate Slug from the Title field. How shall that be done?

Upvotes: 1

Views: 3520

Answers (1)

A. J. Parr
A. J. Parr

Reputation: 8026

There is the django.utils.text.slugify method. If you want to use it you can simple call slugify() on your title. In a serializer you might want to use it like so:

from django.utils.text import slugify

class ExampleSerializer(serializers.ModelSerializer):
    title_slug = serializers.SerializerMethodField()

    def get_title_slug(self, instance):
        return slugify(instance.title)

    class Meta:
        model = Example
        fields = ("title_slug", )

Upvotes: 2

Related Questions