Question

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.

Was it helpful?

Solution

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 }}.

OTHER TIPS

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] + "..."
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top