简体   繁体   English

切片 Django 查询集字段值

[英]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.我通过使用 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.这是很长的内容,所以在后端做这件事将帮助我减少我的 JSON 大小。

This is how my JSON looks like.这就是我的 JSON 的样子。 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.它将新值附加到 json 文件的末尾。 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
]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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