Returning modified data to a template
I need to amend QuerySet data when i return it to a template.
for example, model.objects.all() returns a date (with other fie开发者_开发问答lds), but i also want to return the number of days since that date has passed. This is so that in the template, i can say "you last logged in 4 days ago".
What is the best way to do this?
There's a built-in template filter to do this:
{{ myobject.datefield|timesince }}
But generally for this sort of thing, the easiest way is probably to define a custom method on the model:
def mymethod(self):
today = datetime.datetime.today()
since = today - self.datefield # since is a datetime.timedelta object
return since.days
精彩评论