开发者

Modifying QuerySet result

Is it possible to change some specific items in a QuerySet开发者_如何学Go object? In my case i'm trying to slicing "title" fields with length more than 40 characters and append "..." at the end of field.


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜