切片 Django Queryset 字段值
Slice Django Queryset field value
我的对象有内容字段,实际上是文章的内容。我使用 XHR 将它传递给模板。我不想在前端切片内容。如何通过给出最大字符数限制来分割它?
它的内容很长,所以在后台做它会帮助我减少 JSON 大小。
这就是我的 JSON 的样子。我删除了内容,因为它很长。它将出现在结果列表中。
那是我试过的方法,但没有用。它将新值附加到 json 文件的末尾。但我希望它在结果中将每个附加到每个字典。
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))
您可以像这样pre-process每篇文章的文本字段:
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
]
我的对象有内容字段,实际上是文章的内容。我使用 XHR 将它传递给模板。我不想在前端切片内容。如何通过给出最大字符数限制来分割它?
它的内容很长,所以在后台做它会帮助我减少 JSON 大小。
这就是我的 JSON 的样子。我删除了内容,因为它很长。它将出现在结果列表中。
那是我试过的方法,但没有用。它将新值附加到 json 文件的末尾。但我希望它在结果中将每个附加到每个字典。
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))
您可以像这样pre-process每篇文章的文本字段:
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
]