def add_order(): form = OrderForm() if form.validate_on_submit(): try: products = Product.query.filter( Product.id.in_([product.id for product in form.products.data])) order = Order(client=form.client.data, products=products.all(), total_price=products.with_entities( func.sum(Product.price))) db.session.add(order) db.session.query(Product).filter( Product.id.in_(products.with_entities(Product.id))).update( dict(in_stock=False), synchronize_session='fetch') db.session.commit() return redirect('/add-order') except: db.session.rollback() return render_template('add_order.html', form=form)