gpt4 book ai didi

python - 如何检查查询集是否为空?

转载 作者:行者123 更新时间:2023-12-04 00:33:31 25 4
gpt4 key购买 nike

分页码:

try:
page = paginator.page(page_number)
print(page.object_list)

所以下面的输出是我的分页 print(page.object_list) 的结果:

<QuerySet [<Comment: I can't believe it's happeinig>, <Comment: Just trying to fill up the comments>, <Comment: Another one!>, <Comment: Evenmore noe>, <Comment: Something>, <Comment: Lol>, <Comment: Are comments showing up?>, <Comment: Great for the economy.>, <Comment: honestly>, <Comment: Even though the the onlyEven though the only one to udnertstnaf!>]>
<QuerySet [<Comment: Yeah it's crazy how fast aswell. It's very awesome how it's doing atm. >]>
<QuerySet []>
<QuerySet [<Comment: Sure>, <Comment: No worries>]>
<QuerySet []>
<QuerySet []>
<QuerySet [<Comment: attempt 2!>]>
<QuerySet [<Comment: Attempt 3!>]>
<QuerySet []>
<QuerySet [<Comment: 12>]>
<QuerySet []>
<QuerySet [<Comment: Somewhere?>]>
<QuerySet []>
<QuerySet [<Comment: lol>]>
<QuerySet []>
<QuerySet [<Comment: 12>]>
<QuerySet []>

如您所见,我有空的查询集,这些会导致我的代码出现错误。因此,我想遍历这些查询集并找出空的。我尝试添加这个 for 循环:

for i in page.object_list:
if len(i) < 0:

但我得到一个错误:

TypeError at /news/11/
object of type 'Comment' has no len()

任何帮助表示赞赏。

如果查询集为空,则尝试删除它:

try:
page = paginator.page(page_number)
if page.object_list:
pass
else:
page.delete()

错误:

AttributeError at /news/11/
'CustomPage' object has no attribute 'delete'

最佳答案

您可以使用 if 子句直接测试 QuerySet。这将导致 QuerySet 被评估。空查询集(或空列表)是 falsy:

page = paginator.page(page_number)
if page.object_list:
...

如果您想在 QuerySet 上进行迭代,则无需测试是否为空。只需使用 for 子句:

for obj in page.object_list: # empty QuerySet gets zero iterations
...

关于python - 如何检查查询集是否为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47173451/

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