[Django]-How to take slice of string when serializing a field (Django/DRF)

3👍

There are different approaches, the first one that I prefer is to add a property to your model and add its field to the serializer:

class Article(models.Modle):
    ...
    @property
    def summary(self):
        return self.text[:200]


class ArticleSerializer(serializers.ModelSerializer):                                                                                                                                                               
    summary = serializers.CharField()                                                                                                                                                        

and for the second approach you can use SerializerMethodField:

class ArticleSerializer(serializers.ModelSerializer):                                                                                                                                                               
    summary = serializers.SerializerMethodField() 

    def get_summary(self, obj):
        return obj.text[:200]

2👍

Another approach would be creating your own custom field:

class CustomCharField(serializers.CharField):

    def __init__(self, repr_length, **kwargs):
        self.repr_length = repr_length
        super(CustomCharField, self).__init__(**kwargs)

    def to_representation(self, value):
        return super(CustomCharField, self).to_representation(value)[:self.repr_length]

And use it in serializers:

class ArticleSerializer(serializers.ModelSerializer):
    text = CustomCharField(repr_length=200)
👤zeynel

1👍

I like the ‘CustomCharField’ approach suggested by zeynel. This version uses Django’s Truncator.

from django.utils.text import Truncator
from rest_framework import serializers

class TruncatedCharField(serializers.CharField):
    def __init__(self, length=200, **kwargs):
        self.length = length
        super().__init__(**kwargs)

    def to_representation(self, value):
        repr_ = super().to_representation(value)
        return Truncator(repr_).chars(self.length)

Leave a comment