Checking for empty queryset in Django

前端 未结 7 986
情书的邮戳
情书的邮戳 2020-12-07 07:36

What is the recommended idiom for checking whether a query returned any results?
Example:

orgs = Organisation.objects.filter(name__iexact = \'Fjuk inc\')         


        
7条回答
  •  太阳男子
    2020-12-07 08:24

    I disagree with the predicate

    if not orgs:
    

    It should be

    if not orgs.count():
    

    I was having the same issue with a fairly large result set (~150k results). The operator is not overloaded in QuerySet, so the result is actually unpacked as a list before the check is made. In my case execution time went down by three orders.

提交回复
热议问题