我是一个有用的助手,可以为您翻译文本。
我正在尝试基于Flask会话创建购物车。这个想法很简单:
我正在尝试基于Flask会话创建购物车。这个想法很简单:
- Customer clicks "Add to cart" button with hidden inputs
product_id
andqty
This POST query adds new record in session["cart"] dictionary
[{'qty': '1', 'product_id': '6'}, {'qty': '1', 'product_id': '6'}, {'qty': '1', 'product_id': '6'}]
I catch this fields and append them in session dict by:
session["cart"].append(dict({'product_id': id, 'qty': qty}))
每当有人将产品添加到购物车中,它就会在购物车会话中添加新记录{'product_id': id, 'qty': qty}
。
如何检查此product_id
是否已经存在于字典中,如果是,则仅增加qty
而不会在具有相同product_id
的字典中创建新记录?
我的添加到购物车:
@app.route('/add-to-cart', methods=['GET', 'POST'])
def add_to_cart():
if request.method == 'POST':
id = int(request.form['product_id'])
qty = int(request.form['qty'])
cart_session()
matching = [d for d in session['cart'] if d['product_id'] == id]
if matching:
matching[0]['qty'] += qty
session["cart"].append(dict({'product_id': id, 'qty': qty}))
return redirect(url_for('home'))
解决方案
@app.route('/add-to-cart', methods=['GET', 'POST'])
def add_to_cart():
if request.method == 'POST':
id = int(request.form['product_id'])
qty = int(request.form['qty'])
cart_session()
matching = [d for d in session['cart'] if d['product_id'] == id]
if matching:
matching[0]['qty'] += qty
else:
session["cart"].append(dict({'product_id': id, 'qty': qty}))
return redirect(url_for('home'))
product_id
作为键,qty
作为值的字典会更方便,这样你就可以使用defaultdict(int)
作为你的字典。 - rlbond