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

时间:2017-11-08 07:00:37

标签: python django pagination

分页代码:

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

3 个答案:

答案 0 :(得分:3)

您可以使用 if 子句直接测试QuerySet。这将导致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
   ...

答案 1 :(得分:1)

您可以使用exists(强调我的)

page.object_list.exists()
  

如果QuerySet包含任何结果,则返回True,否则返回False。这会尝试以最简单,最快的方式执行查询,但它确实执行与普通QuerySet查询几乎相同的查询。

     

exists()对于与QuerySet中的对象成员资格相关的搜索以及中查询集中任何对象的存在非常有用,特别是在大型QuerySet 的上下文中。

尽管如此,在创建paginator

之前过滤查询集要好得多

答案 2 :(得分:0)

另一种方式是:

if page.object_list.count() == 0:
  #Empty Result
else:
  #Something