我想在添加之后过滤查询集。见下文
view.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 %}
我遇到的问题是,在执行过滤器时,附加的信息(例如“Hello&#39;”)正在丢失。如果我做以下所有工作正常。
{% for document in documents %}
<p>{{document.hello}}</p>
{% endfor %}
如何通过过滤器传输附加信息。我应该使用自定义模板过滤器而不是在视图中执行吗?
由于
答案 0 :(得分:1)
filter
将创建新的queryset对象。而不是它,你可以用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')