[Django]-Modifying QuerySet result

4👍

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

1👍

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] + "..."

Leave a comment