Checking for empty queryset in Django

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

    To check the emptiness of a queryset:

    if orgs.exists():
        # Do something
    

    or you can check for a the first item in a queryset, if it doesn't exist it will return None:

    if orgs.first():
        # Do something
    
    0 讨论(0)
提交回复
热议问题