I'm trying to create a shopping cart based on sessions on Flask.
Idea is simple:
product_id and qtyThis 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}))
Every time someone add product in cart it add new record {'product_id': id, 'qty': qty} in cart session.
How to check if this product_id already in dictionary and if it does, increment just qty but don't create new record in dictionary with same product_id?
My Add to cart:
@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'))
Solution
@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'))
One easy way in python to look for objects in a list is to use list comprehension:
matching = [d for d in session['cart'] if d['product_id'] == id]
if matching:
matching[0]['qty'] += int(qty)
else:
session['cart'].append(dict({'product_id': id, 'qty': int(qty)}))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With