Home > Software design >  Object is not subscriptable python error django
Object is not subscriptable python error django

Time:05-07

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:

def dispatch(request):
    
events = Event.objects.filter(description="Dispatch").values("element")

starts = Start.objects.all()

ends = End.objects.all()

# subscript error fixed
d_starts = { s.start_id: s for s in start }

# subscript error fixed
d_ends = { c.end_id: c for c in end }

d_start_end_ids = [ { 'start': d_starts[e['element'][52:58]], 
                        'end': d_ends[e['element'][69:75]] } for e in events ]

for d in d_start_end_ids:
    
    # Error is here
data = {'[%s, %s] -> [%s, %s]' % (d['start']['latitude'], 
            d['start']['longitude'], d['end']['latitude'], d['end']['longitude'])}

JsonResponse(data)

I am getting an error saying:

line 33, in dispatch_data
    data = '[%s, %s] -> [%s, %s]' % (d['start']['latitude'], 
                d['start']['longitude'], d['end']['latitude'], d['end']['longitude'])
TypeError: 'Start' object is not subscriptable]

My Start model is:

class Start(models.Model):
    start_id = models.CharField(primary_key=True, max_length=100)
    name = models.CharField(max_length=150)
    latitude = models.FloatField(null=True)
    longitude = models.FloatField(null=True)

CodePudding user response:

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?):

data = {'[%s, %s] -> [%s, %s]' % (d['start'].latitude, 
            d['start'].longitude, d['end'].latitude, d['end'].longitude)}
  • Related