How to modify timestamp format in Django Rest Framework fields

Viewed 36

There's this model:

class Post(models.Model):
    poster = models.ForeignKey('User', on_delete=models.CASCADE, related_name='posts')
    body = models.TextField()
    timestamp = models.DateTimeField(auto_now_add=True)
    likers = models.ManyToManyField('User', blank=True, null=True, related_name='liked_posts')
    savers = models.ManyToManyField('User', blank=True, null=True, related_name='saved_posts')
    likes = models.IntegerField(default=0)

And its Rest serializer:

class PostSerializer(serializers.ModelSerializer):
    class Meta:
        model = Post
        fields = '__all__'

There is a field named timestamp in the model. I used to use a custom serializer function inside the model class so it would return the timestamp as: 'timestamp': self.timestamp.strftime('%b %d %Y, %I:%M %p'). How can I do so using Rest?

1 Answers
class PostSerializer(serializers.ModelSerializer):
    str_timestamp = serializers.SerializerMethodField(
        method_name="get_str_timestamp"
    )    

    class Meta:
        model = Post
        fields = '__all__'

    def get_str_timestamp(self, obj: Post):
        return obj.timestamp.strftime('%b %d %Y, %I:%M %p')
Related