Python列表:列表索引超出范围

时间:2018-03-07 14:45:24

标签: python django python-2.7 django-models

我对python并不是很熟悉,并且从我的一个朋友那里得到了这个代码,并且需要一些社区帮助来解决这个问题。我从下一行得到“list index out of range”错误。

  

days = list(zip(Leave_type.objects.filter(type = leavetype).values_list('max_days',flat = True))[0])

注意:我已经执行了迁移并设置了我的数据库。

def timeoffapply(request):

if not request.session.get('id', None):
    return render(request, 'login.html')
else:
    stdate = request.POST['startDate']
    enddate = request.POST['endDate']
    leavetype = request.POST['leaveType']
    days = list(zip(Leave_type.objects.filter(type=leavetype).values_list('max_days', flat=True))[0])
    d1 = datetime.strptime(stdate, "%Y-%m-%d")
    d2 = datetime.strptime(enddate, "%Y-%m-%d")
    d3 = abs((d2 - d1).days)+1
    empid = (request.session['id'])[0]
    countdays = Leave.objects.filter(Emp_id = empid,type=leavetype).aggregate(Sum('days'))
    if countdays['days__sum'] == None:
        finaday = (days[0] - 0)
    else:
        finaday=(days[0] - countdays['days__sum'])
    if enddate>=stdate:
        if finaday >= d3:
            getleaveid = list(zip(Leave_type.objects.filter(type=leavetype).values_list('id', flat=True))[0])
            split_lt_id = ("".join(str(e) for e in getleaveid))
            empid = (request.session['id'])[0]
            get_emp_name = list(zip(Employee.objects.filter(id=empid).values_list('name', flat=True))[0])
            get_emp_name = ("".join(str(e) for e in get_emp_name))
            empid = (request.session['id'])[0]
            leave_id = Leave.objects.all().count()
            test = Leave(id=(leave_id + 1), name=get_emp_name, type=leavetype, start_date=stdate, end_date=enddate,
                         days=d3,
                         status="pending")

            test.Emp_id_id = empid
            test.leave_type_id_id = split_lt_id
            test.save()
            return HttpResponseRedirect('/')
        else:
            qs = Leave.objects.all().filter(Emp_id=(request.session['id'])[0])
            context = {
                "qs": qs,
                "error": "true",
                "msg": "You are allowed to have holidays for " + str(finaday) + " days in " +str(leavetype)
            }
            return render(request, 'timeoff.html', context)

2 个答案:

答案 0 :(得分:2)

可能存在从Leave_type.objects.filter(type=leavetype).values_list('max_days', flat=True)返回的列表为空并且您使用[0]访问空列表中的第一个元素的情况。因此导致list index out of range错误。

答案 1 :(得分:1)

问题只是从Leave_type模型返回的查询集为空;因此你无法访问它。