I have this function where i am using models ‘Start’ and ‘End’ that contain fields latitude and longitude.. and I am trying to match them with a field called elements that I am using subscript to extract the start_id and end_id and match them with ‘Start’ and ‘End’
The function in question that is giving me a subscript error is:
JavaScript
x
25
25
1
def dispatch(request):
2
3
events = Event.objects.filter(description="Dispatch").values("element")
4
5
starts = Start.objects.all()
6
7
ends = End.objects.all()
8
9
# subscript error fixed
10
d_starts = { s.start_id: s for s in start }
11
12
# subscript error fixed
13
d_ends = { c.end_id: c for c in end }
14
15
d_start_end_ids = [ { 'start': d_starts[e['element'][52:58]],
16
'end': d_ends[e['element'][69:75]] } for e in events ]
17
18
for d in d_start_end_ids:
19
20
# Error is here
21
data = {'[%s, %s] -> [%s, %s]' % (d['start']['latitude'],
22
d['start']['longitude'], d['end']['latitude'], d['end']['longitude'])}
23
24
JsonResponse(data)
25
I am getting an error saying:
JavaScript
1
5
1
line 33, in dispatch_data
2
data = '[%s, %s] -> [%s, %s]' % (d['start']['latitude'],
3
d['start']['longitude'], d['end']['latitude'], d['end']['longitude'])
4
TypeError: 'Start' object is not subscriptable]
5
My Start model is:
JavaScript
1
6
1
class Start(models.Model):
2
start_id = models.CharField(primary_key=True, max_length=100)
3
name = models.CharField(max_length=150)
4
latitude = models.FloatField(null=True)
5
longitude = models.FloatField(null=True)
6
Advertisement
Answer
Keep in mind that in your for loop the variables d['start']
and d['end']
each contain an instance of the Start
model. To manipulate the fields of an instance you should use the dot .
(you should use subscript when dealing with subscriptable objects – see What does it mean if a Python object is “subscriptable” or not?):
JavaScript
1
3
1
data = {'[%s, %s] -> [%s, %s]' % (d['start'].latitude,
2
d['start'].longitude, d['end'].latitude, d['end'].longitude)}
3