<p>是的,您可以重用现有的查询集。</p>
<pre><code>everyone = User.objects.filter(is_active=True)
active_not_deleted = everyone.filter(is_deleted=False)
active_is_deleted = everyone.filter(is_deleted=True)
</code></pre>
<p>这实际上并没有提高任何速度,但事实上,这个代码块甚至不会对数据库执行查询,因为Django QuerySets的计算很懒。我的意思是,在您真正需要这些值之前,它不会将查询发送到数据库。下面是一个与数据库对话的示例。</p>
<pre><code>everyone = User.objects.filter(is_active=True) # Building SQL...
active_not_deleted = everyone.filter(is_deleted=False) # Building SQL...
active_is_deleted = everyone.filter(is_deleted=True) # Building SQL...
# Example of the whole queryset being evaluated
for user in everyone:
# This will execute the query against the database to return the list of users
# i.e. "select * from user where is_active is True;"
print(user)
# Example of using iterator to evaluate one object at a time from the queryset.
for user in active_not_deleted.iterator():
# This will execute the query for each result, so it doesn't
# load everything at once and it doesn't cache the results.
# "select * from user where is_active is True and is_deleted is False limit 1 offset 0;"
# The offset is incremented on each loop and another query is sent to retrieve the next user in the list.
print(user)
</code></pre>
<p>推荐阅读:</p>
<ul>
<li><a href="https://docs.djangoproject.com/en/1.11/topics/db/queries/#querysets-are-lazy" rel="noreferrer">https://docs.djangoproject.com/en/1.11/topics/db/queries/#querysets-are-lazy</a></li>
<li><a href="https://docs.djangoproject.com/en/1.11/ref/models/querysets/#iterator" rel="noreferrer">https://docs.djangoproject.com/en/1.11/ref/models/querysets/#iterator</a></li>
<li><a href="https://docs.djangoproject.com/en/1.11/topics/db/queries/#caching-and-querysets" rel="noreferrer">https://docs.djangoproject.com/en/1.11/topics/db/queries/#caching-and-querysets</a></li>
</ul>
<p>作为这个答案的补充,如果您真的需要,可以进行一个查询,然后用Python进行过滤。请注意,不能对列表进行后续筛选,因为它们不是queryset。</p>
<pre><code>everyone = User.objects.filter(is_active=True)
active_not_deleted = list(filter(lambda user: user.is_deleted is False), list(everyone))
active_is_deleted = list(filter(lambda user: user.is_deleted is True), list(everyone))
</code></pre>
<p>在最后一个示例中,<code>everyone</code>是一个queryset,而<code>active_not_deleted</code>和<code>active_is_deleted</code>是用户对象的Python列表。在第一个<code>list(everyone)</code>调用中,只对<code>everyone</code>queryset求值一次,然后缓存结果。</p>