简体   繁体   中英

Slice Django Queryset field value

My object has content field which is actually content of the article. I am passing it to template by using XHR. I don't want to slice content in front end. How can I slice it by giving a maximum character limit?

It is very long content so doing it in backend will help me to reduce my JSON size.

This is how my JSON looks like. I deleted content because it is very long. It will be in results list.

在此处输入图片说明

That's what I tried and it didn't work. It appends the new values to the end of the json file. But I want it to append each to each dictionary in results.

articles1 = Article.objects.all().values('title', 'tags', 'main_img', 'read_time', 'last_updated', 'slug').order_by('-last_updated')
    articles2 = Article.objects.all().values('content')
    short_content = [article['content'][3:100] for article in articles2]
    articles = list(chain(articles1, short_content))

You can pre-process each article's text field like this:

def shorten_content(article_values):
    article_values["content"] = article_values["content"][3:100]
    return article_values

article_queryset = Article.objects.values(
    'title', 'content', 'tags', 'main_img',
    'read_time', 'last_updated', 'slug'
).order_by('-last_updated')

articles = [
    shorten_content(article) for article in article_queryset
]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM