首页 > 解决方案 > 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 %}

如何通过过滤器传输附加信息。我应该使用自定义模板过滤器而不是在视图中执行它吗?

谢谢

标签: pythondjango

解决方案


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')

推荐阅读