Is it possible to change some specific items in a QuerySet object? In my case i'm trying to slicing "title" fields with length more than 40 characters and append "..." at the end of field.
+2
A:
There are 2 ways of doing what you want.
The first is to use a Django filter. So if you are looping through the items of your queryset and displaying them on a page use something like truncatewords. You would use this like this in your template:
{% for item in queryset %}
<h1>{{ item.title|truncatewords:3 }}</h1>
{% endfor %}
It doesn't look like there is a Django filter for truncating base on the number of characters. If you want to write your own filter it's not that hard to do.
The other option is to put a method on your model to do what you want. Here is an example:
@property
def short_title(self):
return '%s...' % self.title[:40]
You would then be able to reference this anywhere in your template as {{ object.short_title }}.
sheats
2009-11-19 15:38:04
Thank you, added to my own /r/todayilearned
sadegh
2009-11-19 16:17:28
+1
A:
I suggest adding a new property 'adjusted_title' to each object
for item in your_query_set:
if(len(item.title) > 40):
item.adjusted_title = item.title[0:40] + "..."
This would work, but could mean an unnecessary loop through the queryset. It's probably better to just put the logic in a method on the model like I suggested to save an unnecessary loop and in case the logic is needed somewhere else.
sheats
2009-11-19 15:47:26