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.
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
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.