开发者

Returning modified data to a template

开发者 https://www.devze.com 2022-12-29 13:06 出处:网络
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 th

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
0

精彩评论

暂无评论...
验证码 换一张
取 消