Checking for empty queryset in Django

前端 未结 7 1000
情书的邮戳
情书的邮戳 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:18

    Since version 1.2, Django has QuerySet.exists() method which is the most efficient:

    if orgs.exists():
        # Do this...
    else:
        # Do that...
    

    But if you are going to evaluate QuerySet anyway it's better to use:

    if orgs:
       ...
    

    For more information read QuerySet.exists() documentation.

提交回复
热议问题