Reputation: 5655
I faintly remember seeing this done before in tutorials in the past. However, im having trouble finding out exactly how in the docs currently.
Suppose we had a model called Post. This model has a field called timestamp. However, when we send this model into the template we don't care about timestamps. Instead, we want the more popular "age" (created X mins/hrs ago), which thankfully, can be deduced from the timestamp.
Instead of creating a whole new field for timestamp, and instead of using custom template tags, can we somehow add a field to a model temporarily before sending it over to our template?
Ex.
# views.py
# Is the below code right? do I need to save()?
posts = Posts.objects.filter(...).filter(...)[:X]
for post in posts:
# Post does not have an age field, we are creating one
# temporarily before sending it to the template
post.age = some_function(post.timestamp)
return render_to_response(template, {'posts' : posts}, etc...)
Thank you.
Upvotes: 2
Views: 92
Reputation: 798754
Just make it a property on the model.
class Post(Model)
@property
def age(self):
return now() - self.timestamp
Upvotes: 6