Home > Software engineering >  "TypeError: NoneType is not subscriptable" when executing multiple queries
"TypeError: NoneType is not subscriptable" when executing multiple queries

Time:11-16

Member function that retrieves db.

def GetDb(self):
    db = getattr(g, '_database', None)
    if db is None:
        db = g._database = sqlite3.connect(self.path)       
        db.row_factory = sqlite3.Row         
    return db

Member function that returns list from db queries

def GetOrderItemsList(self, orderid):
    list = []
    with app.app_context():
        db = self.GetDb()             
        cur = db.execute('SELECT * FROM ordersList WHERE orderId = ?',[orderid])
        records = cur.fetchall(); 
        for row in records:                
            print(row)
            invid = row['inventoryId']
            OrderItem 
            OrderItem.orderId = row['orderId']
            OrderItem.productId = row['inventoryId']             
            OrderItem.productName = 'none'
            OrderItem.quantity = row['quantity']
            OrderItem.productPrice = row['price'] 
            nextcur = db.execute('SELECT * FROM inventory WHERE invId = ?', [invid]) 
             
            #nextcur = db.execute('SELECT * FROM inventory WHERE invId = 1') #works
            res = nextcur.fetchone();
            OrderItem.productName = res['invName']
            print(res['invName'])                
            list.append(OrderItem)


    return list

OrderItem:

class OrderItem(object):     
     def __init__(self, ordId, invId, name, quantity, price):
         self.orderId = ordId
         self.productId = invId
         self.productName = name
         self.quantity = quantity
         self.productPrice = price

Error message:

Traceback error
OrderItem.productName = res['invName']
TypeError: 'NoneType' object is not subscriptable

Error

nextcur = db.execute('SELECT * FROM inventory WHERE invId = ?', [invid]) 

Works

nextcur = db.execute('SELECT * FROM inventory WHERE invId = 1')

Been fighting this for many hours. Searching on google. Reading questions on here.

Any help would be appreciated.

CodePudding user response:

The error

'NoneType' object is not subscriptable

Means that you're trying to access an object's key of an object that doesn't exist, i.e. the object is None.

Please check that here

[invid]

invid is not None, i.e. print (invid)

Also, the issue could be that here

res['invName']

res is None, please check the contents of res (with print, etc) before accessing invName, as it is None.

  • Related