gpt4 book ai didi

python - 查询后可以过滤查询集吗? Django

转载 作者:IT老高 更新时间:2023-10-29 00:11:37 25 4
gpt4 key购买 nike

对不起,如果这个问题听起来很奇怪。我只是想知道当我已经有一个查询集时是否可以创建新的查询集。

例如这里...

 everyone = User.objects.filter(is_active=True)  # this would of course return all users that's active
not_deleted = User.objects.filter(is_active=True, is_deleted=False) # return user that's active and not deleted
is_deleted = User.objects.filter(is_active=True, is_deleted=True) # return user that's active and is already deleted

我的问题是...对于 not_deletedis_deleted 他们都处于事件状态是真的,与 everyone 是一样的可能的方式来使用 everyone 然后以某种方式过滤掉 is_deleted=Trueis_deleted=False?那么我相信如果可能的话,查询会更快更好,对吧?

everyonenot_deletedis_deleted 这三个变量随后将用于其他用途。

希望我把我的问题说得很清楚。

提前致谢。

最佳答案

是的,您可以重复使用现有的查询集。

everyone = User.objects.filter(is_active=True)
active_not_deleted = everyone.filter(is_deleted=False)
active_is_deleted = everyone.filter(is_deleted=True)

虽然这并没有真正使任何事情变得更快,事实上,这个代码块甚至不会对数据库执行查询,因为 Django QuerySet 是延迟评估的。我的意思是,在您真正需要这些值之前,它不会将查询发送到数据库。这是一个与数据库对话的示例。

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)

推荐阅读:

作为此答案的补充,您可以进行单个查询,然后根据需要在 Python 中进行过滤。请注意,您无法对列表进行后续过滤,因为它们不是 QuerySet。

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

在最后一个示例中,everyone 是一个查询集,active_not_deletedactive_is_deleted 是用户对象的 Python 列表。 everyone 查询集只会在第一个 list(everyone) 调用中计算一次,然后将结果缓存。

关于python - 查询后可以过滤查询集吗? Django ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45228187/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com