TypeError:“机架”对象不可下标

时间:2019-05-08 05:05:24

标签: python python-3.x sqlalchemy

def draw(self):
    racks = DBSession.query(Rack)
    dwg = svgwrite.Drawing(filename='name', size=(162, 72), debug=True)
    shapes = dwg.add(dwg.g(id='shapes', fill='red'))
    for rack in racks:
        r_l = rack['length']
        r_w = rack['width']

我有一个列表,其中包含json对象。当我尝试通过键访问其值时,出现此错误:

r_l = rack['length']

TypeError: 'Rack' object is not subscriptable

这是对racks = DBSession.query(Rack):

的答复
<class 'list'>: [{'angle': 0.0, 'longitude': 20.0, 'latitude': 20.0, 'width': 4.0, 'id': 1, 'shelves': [{'id': 1, 'isOrthogonal': True, 'longitude': 21.0, 'rackId': 1, 'width': 0.5, 'latitude': 21.0, 'qr': 'localhost:8080/assets/images/image-9b286d8b-d017-47a4-9e7e-3edc14b3932f.jpeg?_ts=1557292062.929329', 'code': 'R1SH1', 'length': 1.0}, {'id': 2, 'isOrthogonal': True, 'longitude': 21.0, 'rackId': 1, 'width': 0.5, 'latitude': 19.0, 'qr': 'localhost:8080/assets/images/image-61fb6cb8-3047-4a36-a4b2-65c07b20f900.jpeg?_ts=1557292062.951592', 'code': 'R1SH2', 'length': 1.0}], 'length': 2.0}, {'angle': 90.0, 'longitude': 40.0, 'latitude': 40.0, 'width': 2.0, 'id': 2, 'shelves': [{'id': 3, 'isOrthogonal': True, 'longitude': 41.0, 'rackId': 2, 'width': 0.5, 'latitude': 40.0, 'qr': 'localhost:8080/assets/images/image-0d569eab-933d-464a-843f-dee26fb9a34f.jpeg?_ts=1557292062.969998', 'code': 'R2SH3', 'length': 1.0}, {'id': 4, 'isOrthogonal': True, 'longitude': 39.0, 'rackId': 2, 'width': 0.5, 'latitude': 40.0, 'qr': 'localhost:8080/assets/images/image-a1eb6db0-9d3e-40d7-99e7-13965fd1cb34.jpeg?_ts=1557292062.9888701', 'code': 'R2SH4', 'length': 1.0}], 'length': 2.0}]

1 个答案:

答案 0 :(得分:1)

如错误本身所述,您需要使用instancename.attribute
访问属性 错误显示为TypeError: 'Rack' object is not subscriptable,因此类的实例的属性需要像这样由.运算符访问

def draw(self):
    racks = DBSession.query(Rack)
    dwg = svgwrite.Drawing(filename='name', size=(162, 72), debug=True)
    shapes = dwg.add(dwg.g(id='shapes', fill='red'))
    for rack in racks:
        #Using instancename.attribute to access attributes
        r_l = rack.length
        r_w = rack.width