0

Here I just wants to annotate a field on a model that gives human readable format saying how much time elapsed since it's created

My Model is created 30 seconds ago

My Model Description:

from django.db import models 
class MyModel(models.Model):
    name = models.CharField(max_length=100)
    created_at = models.DateTimeField(auto_now_add=True)

class Meta:
    ordering = ['-created_at']

@property
def natural_time(self):
    return naturaltime(self.created_at)

What I did is here

from django.contrib.humanize.templatetags.humanize import naturaltime
from django.db.models import F
from .models import MyModel
m = MyModel.objects.annotate(timesincecreated=naturaltime(F('created_at'))
print m.values('timesincecreated')

on this print call I am getting the DateTimeField that I used in the model. But If I want to access the property.

from .models import MyModel
m= MyModel.objects.first()
print m.natural_time

It works.

Any help? TIA.

Raju Ahmed Shetu
  • 134
  • 2
  • 13

1 Answers1

1

You cannot use naturaltime function for annotation, annotation is a computation that is done on database level.

Django provides only a set of basic computations which can be processed by the database like Count, Sum, Min, Max, etc. You can refer to official doc to learn more about Query Expressions.

Tiny.D
  • 6,466
  • 2
  • 15
  • 20
  • Yes I discovered it later.I guess I would be passing the date as it is. I think I should be using ```moment.js``` for frontend to do that. – Raju Ahmed Shetu May 24 '17 at 05:22
  • you can pass as date then use either `naturaltime` or `timesince` in your template, no need do it in javascript. – Tiny.D May 24 '17 at 05:32
  • I am just building REST Api. And the frontend is using other framework. so.. I guess that's the only solution I can have. – Raju Ahmed Shetu May 24 '17 at 05:37