对象不可订阅 python 错误 django

Object is not subscriptable python error django

我有这个功能,我正在使用包含字段纬度和经度的模型 'Start' 和 'End'.. 我正在尝试将它们与我正在使用下标的名为元素的字段匹配提取 start_id 和 end_id 并将它们与 'Start' 和 'End'

匹配

给我下标错误的相关函数是:

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)

我收到一条错误消息:

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]

我的启动模型是:

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)

请记住,在您的 for 循环中,变量 d['start']d['end'] 每个都包含 Start 模型的一个实例。要操作实例的字段,您应该使用点 .(处理可下标对象时应使用下标 - 请参阅 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)}