簡體   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