[Django]-How to use django.contrib.humanize filter in DRF serializers

4👍

Yes, you can pass the data through the naturaltime filter, with:

from django.contrib.humanize.templatetags.humanize import naturaltime

def to_representation(self, instance):
    representation = super().to_representation(instance)
    representation['last_login'] = naturaltime(instance.last_login)
    return representation

Note that Django’s naturaltime uses a non-breaking space [wiki] between a number and its unit, not a normal space, so:

>>> naturaltime(datetime(2019, 11, 25))
'2\xa0years, 2\xa0months ago'

Leave a comment