bp = Blueprint('store', __name__)
@bp.route('/cart/<product_id>')
def add_to_cart(product_id):
print(session)
if "order_id" in session:
print(session["order_id"])
order = Order.query.get(session["order_id"])
# add products to order object ...
else:
order = Order()
db.session.add(order)
db.session.commit()
session["order_id"] = order.order_id
session.modified = True
return redirect(url_for('store.products'))
@bp.route('/', methods=['GET', 'POST'])
def products():
print(session)
当用户第一次添加到购物车时,我创建了一个新订单,并将该订单的order_id(一个整数)保存在会话中,以向该订单添加产品。 然后,当他们添加到购物车时,我可以查询订单并向其中添加产品。
但是,在重定向到store.products页面的请求之后,会话将重置为空字典。 我不确定如何实现该会话,以便它在所有请求中均保持不变并使用它来跟踪order_id。
我的订单表定义为:
class Order(db.Model):
__tablename__ = 'Orders'
order_id = db.Column(db.Integer, primary_key=True)
products = db.relationship('Product', secondary=cart, back_populates='orders')
customer_id = db.Column(db.Integer, db.ForeignKey('Customers.customer_id'))
customer = db.relationship('Customer', back_populates='orders')
quantities = db.relationship('Quantity')
message = db.Column(db.Text)