is it possible to use the Django humanize filter for drf on the serializers
i have tried putting naturaltime in the to_representation method like below
def to_representation(self, instance):
representation = super(ListUsersSerializer,
self).to_representation(instance)
representation['last_login'] = instance.last_login(naturaltime)
but it didn't work
CodePudding user response:
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'
