The user selects two aircraft to compare from the list page. However I get the following error: IndexError at /delta/ list index out of range .
It's complaining about this line in particular:
first_value = getattr(aircraft_to_compare[0], key)
Is there an obvious error that I'm making here?
View
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
})
IndexError at /delta/ list index out of range. means that there is not data that was found by your model. You might want to look into your db to see whether those Ids
exist or not. As per your code, there are no errors, so plz look at Aircraft.objects.filter(id__in=ids)
a little more in deep.
Also its a good approach to use len(aircraft_to_compare)
to check whether any data is present or not.
Hope this helps.
You may not have found any records in the query
aircraft_to_compare = Aircraft.objects.filter(id__in=ids)
Check the length of aircraft_to_compare
or use try...except
block while accessing items from that queryset.
In Views, You are creating a list data=[]
, then you are appending some values in that list. So the problem is when the list is appended to its max length there is no space left to append more values "list out of range". You can try to make the list empty after each operation(comparison) using data.clear() .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.