Reputation: 647
I would like to have a field in my model which representation is automatically adjusted based in its value. Suppose I have this toy model:
class Article(models.Model):
title = models.CharField(max_lenght=256)
visits = models.PositiveIntegerField(default=0)
I would like to write in my templates just {{article.visits}}
and, if the value is (for example), 45, it will render "45", but if the value is 1233, it will print "1.2k".
This is simple using template filters for formating, but I would like to do it automatically in any case. is it possible? What do you suggest?
Upvotes: 0
Views: 498
Reputation: 45575
Add a property to the Article
model:
class Article(models.Model):
...
@property
def visits_display(self):
return self.visits if visits < 1000 else '%.1fk' % (self.visits/1000.0)
And use this property in the template:
{{ article.visits_display }}
Upvotes: 3