Checking for empty queryset in Django

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

提交回复
热议问题