【发布时间】:2019-10-06 22:44:41
【问题描述】:
我声明了一个名为 add_to_cart(db, itemid, quantity) 的方法。每当调用该方法时,它都会在数据库中查找会话数据。会话数据包含字典列表。此方法的目的是为列表创建一个新条目(字典)或更新现有条目的值。 字典有以下键:id,数量
到目前为止,我已经开发了以下代码。首先,从数据库中获取数据后,我将 itemid 与字典键匹配:'id'。如果 itemid 与字典的任何值都不匹配,那么它将向该列表追加一个新字典。
def add_to_cart(db, itemid, quantity):
# ......
row = cursor.fetchone()
if row is not None:
cart = json.loads(row['data'])
for dic in cart:
if str(dic.get("id")) == str(itemid):
dic['quantity'] = int(dic['quantity']) + quantity
data = json.dumps(cart)
# update the 'data' to the database
break
else:
if counter == len(cart):
item = {
'id': itemid,
'quantity': quantity
}
cart.append(item)
data = json.dumps(cart)
# update the 'data' to the database
break
让初始购物车是这样的:
[{'id': '40', 'quantity': '2'}, {'id': '41', 'quantity': '5'}]
当我将 1 件商品 40 添加到购物车时,应该是这样的:
[{'id': '40', 'quantity': '3'}, {'id': '41', 'quantity': '5'}]
但我得到了:
[{'id': '40', 'quantity': '2'}, {'id': '41', 'quantity': '5'}, {'id': '40', '数量': '1'}]
【问题讨论】:
标签: python mysql python-3.x sqlite