返回顶部

Django报错ZeroDivisionError: division by zero

Django报错ZeroDivisionError: division by zero

DJango报错:up_rate = round(upline/total*100) ZeroDivisionError: division by zero

 

 报错代码

#报错代码
def dashboard(request):
    total = models.Asset.objects.count()
    upline = models.Asset.objects.filter(status=0).count()
    offline = models.Asset.objects.filter(status=1).count()
    unknown = models.Asset.objects.filter(status=2).count()
    breakdown = models.Asset.objects.filter(status=3).count()
    backup = models.Asset.objects.filter(status=4).count()
    up_rate = round(upline/total*100)
    o_rate = round(offline/total*100)
    un_rate = round(unknown/total*100)
    bd_rate = round(breakdown/total*100)
    bu_rate = round(backup/total*100)
    server_number = models.Server.objects.count()
    networkdevice_number = models.NetworkDevice.objects.count()
    storagedevice_number = models.StorageDevice.objects.count()
    securitydevice_number = models.SecurityDevice.objects.count()
    software_number = models.Software.objects.count()

    return render(request, 'dashboard.html', locals())

错误分析

这个错误是因为分母 total 的值为零,导致除法运算出现了除以零的情况。你需要检查一下 total 的计算方式,确保它不会为零。如果 total 可能为零,你可以在代码中添加一些逻辑,以避免出现除以零的情况。例如,你可以在分母为零时返回一个默认值或者进行其他的处理。

解决问题 

使用了一个三目运算符来判断 total 是否为零,并在分母为零时返回了一个默认值

解决示例代码

def dashboard(request):
    total = models.Asset.objects.count()
    upline = models.Asset.objects.filter(status=0).count()
    offline = models.Asset.objects.filter(status=1).count()
    unknown = models.Asset.objects.filter(status=2).count()
    breakdown = models.Asset.objects.filter(status=3).count()
    backup = models.Asset.objects.filter(status=4).count()
    up_rate = round(upline/total*100) if total != 0 else 0
    o_rate = round(offline/total*100) if total != 0 else 0
    un_rate = round(unknown/total*100) if total != 0 else 0
    bd_rate = round(breakdown/total*100) if total != 0 else 0
    bu_rate = round(backup/total*100) if total != 0 else 0
    server_number = models.Server.objects.count()
    networkdevice_number = models.NetworkDevice.objects.count()
    storagedevice_number = models.StorageDevice.objects.count()
    securitydevice_number = models.SecurityDevice.objects.count()
    software_number = models.Software.objects.count()

    return render(request, 'dashboard.html', locals())

 因为没有数据所以没有显示百分比,至此问题解决

 

posted @ 2023-10-09 22:27  九尾cat  阅读(132)  评论(0编辑  收藏  举报