python - Django - 附加到查询集后过滤查询集
问题描述
添加到查询集后,我想过滤查询集。见下文
视图.py
documents = Document.objects.all()
for document in documents:
document.hello = "Hello"
# Lots more happens here like carrying out more querying and appending things on to document
drawings = documents.filter(type='d')
schedules = documents.filter(type='s')
# Context.... render... etc..
模板
{% for document in drawings %}
<p>{{document.hello}}</p>
{% endfor %}
{% for document in schedules %}
<p>{{document.hello}}</p>
{% endfor %}
我遇到的问题是附加信息(如“你好”)在执行过滤器时丢失了。如果我执行以下操作,一切正常。
{% for document in documents %}
<p>{{document.hello}}</p>
{% endfor %}
如何通过过滤器传输附加信息。我应该使用自定义模板过滤器而不是在视图中执行它吗?
谢谢
解决方案
filter
将创建新的查询集对象。取而代之的是,您可以使用 Python 进行过滤:
for document in documents:
document.hello = "Hello"
# Lots more happens here like carrying out more querying and appending things on to document
drawings = [document for document in documents if document.type == 'd']
schedules = [document for document in documents if document.type == 's']
context = {'documents': documents, 'drawings': drawings, 'schedules': schedules}
您需要将新列表添加到上下文中以在模板中使用它们:
{% for document in drawings %}
<p>{{document.hello}}</p>
{% endfor %}
UPD
或者你可能想要使用它来代替它annotation
:
from django.db.models import CharField, Value
documents=Document.objects.annotate(hello=Value('hello',output_field=CharField()))
drawings=documents.filter(type='d')
schedules=documents.filter(type='s')
推荐阅读
- c# - 如何在 C# 中创建字段名称的动态总计?
- java - 无法解析值“file:${AppPropertyDir}/context.properties”中的占位符“AppPropertyDir”
- boto3 - 使用 boto3 设置公共 IP 地址
- wix - Wix 安装程序在构建期间复制文件而不是安装
- r - 用 between() 循环
- bash - 用于运行 dotnet 命令行应用程序的 Bash 脚本将 ' 作为 cli 参数
- c# - Dapper 映射问题
- c# - .xmla 使用 C# 部署到 SQL
- python - Keras 双向 LSTM:传递了与 `cell.state_size 不兼容的初始状态`
- python - PXSSH 截断发送到远程服务器的命令