views:

21

answers:

1

I need to amend QuerySet data when i return it to a template.

for example, model.objects.all() returns a date (with other fields), 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?

A: 

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
Daniel Roseman