首页 > 解决方案 > Django python ValueError: no enough values to unpack (expected 2, got 1)

问题描述

我的views.py中有这段代码将导出到excel,我在1个循环中组合了两个查询,但我收到了这个错误Exception Type: ValueError at /export_reportF/ Exception Value: not enough values to unpack (expected 2, got 1)

    reports = TrEmployeeSuppliersFeedbackQuestionsSubmittedRecords.objects.filter(
        fmCustomerID__company_name__in=company.values_list('fmCustomerID__company_name')).order_by('-inputdate')
    daily = FmCustomerEmployeeSupplier.objects.filter(id__in=reports.values_list('fmCustomerEmployeeSupplierID'))
    pairs = [reports, daily]

    for report, day in pairs:
        writer.writerow(
            [
                smart_str(report.id),
                smart_str(report.dateSubmitted),
                smart_str(report.fmCustomerEmployeeSupplierID),
                smart_str(day.fmCustomerLocationID),
                smart_str(day.contact_number),
                smart_str(day.fmCustomerSectionID),
                smart_str(day.bodyTemperature),
                smart_str(report.q1Answer),
                smart_str(report.q2Answer),
            ]
        )

    return response

这是回溯Exception Type: ValueError at /export_reportF/ Exception Value: not enough values to unpack (expected 2, got 1)

Traceback:

File "C:\Users\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py" in inner
  34.             response = get_response(request)

File "C:\Users\Desktop\ContractTracingProject\TracingSettings\TracingApp\views.py" in export_reportF
  1301.     for report, day in pairs:

Exception Type: ValueError at /export_reportF/
Exception Value: not enough values to unpack (expected 2, got 1)

标签: pythondjango

解决方案


第 3 行读取

pairs = [reports, daily]

这给你的是一个包含两个列表的列表。如果你循环它,它会循环两次,首先给你报告列表,然后是每日列表。尝试这个:

for item in pairs:
    print(item)
    print(type(item))

这应该使问题显而易见。解决方案是将第 3 行替换为:

pairs = zip(reports, daily)

这将为您提供可迭代的对,其中每一对都有一份报告和一天。


推荐阅读