繁体   English   中英

/delta/ 处的索引错误 - 列表索引超出范围 - Django

[英]IndexError at /delta/ - list index out of range - Django

用户从列表页面中选择两架飞机进行比较。 但是我收到以下错误: IndexError at /delta/ list index out of range

它特别抱怨这一行:

first_value = getattr(aircraft_to_compare[0], key) 

我在这里犯了一个明显的错误吗?

看法

def aircraft_delta(request):
  ids = [id for id in request.GET.get('ids') if id != ',']
  aircraft_to_compare = Aircraft.objects.filter(id__in=ids)

  property_keys = ['name', 'manufacturer', 'aircraft_type', 'body', 'engines',
                   'image', 'cost','maximum_range','passengers','maximum_altitude','cruising_speed',
                   'fuel_capacity','description','wing_span','length']

  column_descriptions = {
    'image': '',
    'name': 'Aircraft',
    'maximum_range': 'Range (NM)',
    'passengers': 'Passengers',
    'cruising_speed': 'Max Speed (kts)',
    'fuel_capacity': 'Fuel Capacity',
    'aircraft_type': 'Type',
    'body':'Body',
    'engines':'Engines',
    'cost':'Cost',
    'maximum_altitude':'Maximum Altitude',
    'description':'Description',
    'manufacturer':'Manufacturer',
    'wing_span':'Wing Span (FT)',
    'length':'Total Length (FT)'
  }

  data = []

  for key in property_keys:
    row = [column_descriptions[key]]


    first_value = getattr(aircraft_to_compare[0], key)
    second_value = getattr(aircraft_to_compare[1], key)

    if key not in ['image', 'name']:
        delta = abs(first_value - second_value)
    else:
        delta = ''

    row.append(first_value)
    row.append(delta)
    row.append(second_value)

    data.append(row)

  return render(request, 'aircraft/aircraft_delta.html', {
    'data': data
  })

/delta/ 列表索引超出范围的索引错误。 意味着您的模型没有找到数据。 您可能想查看您的数据库以查看这些Ids是否存在。 根据您的代码,没有错误,所以请更深入地查看Aircraft.objects.filter(id__in=ids)

这也是使用len(aircraft_to_compare)检查是否存在任何数据的好方法。

希望这可以帮助。

您可能没有在查询中找到任何记录

aircraft_to_compare = Aircraft.objects.filter(id__in=ids)

检查aircraft_to_compare的长度或在访问来自该查询集的项目时使用try...except块。

在视图中,您正在创建一个列表data=[] ,然后在该列表中附加一些值。 所以问题是当列表附加到其最大长度时,没有剩余空间可以附加更多“列表超出范围”的值。 您可以尝试在每次操作(比较)后使用data.clear() .将列表清空data.clear() .

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM