为了账号安全,请及时绑定邮箱和手机立即绑定

为什么只删除产品,而不删除其相关动作?

为什么只删除产品,而不删除其相关动作?

皈依舞 2023-08-22 16:30:37
我试图从产品表中删除产品,同时也从产品移动表中删除该产品的所有移动(称为移动),但仅删除产品,而不删除其移动。有谁知道为什么?这是代码:@app.route('/products/<int:product_id>/delete', methods=['GET', 'POST'])   def delete_product(product_id):    product = Product.query.get_or_404(product_id)    movements = Movement.query.filter_by(product_id=product_id).all()    for movement in movements:        db.session.delete(movement)    db.session.delete(product)    db.session.commit()    flash('The product has been deleted!', 'success')    return redirect(url_for('products'))这是产品表的模型:class Product(db.Model):    id = db.Column(db.Integer, primary_key=True)    name = db.Column(db.String(50), unique=True, nullable=False)    product_movements = db.relationship('Movement', backref='item', lazy=True)这是运动表:class Movement(db.Model):    id = db.Column(db.Integer, primary_key=True)    product_id = db.Column(db.Integer, db.ForeignKey('product.id'))    product = db.Column(db.String(50), nullable=False)    from_location_id = db.Column(db.Integer, db.ForeignKey('location.id'))    from_location = db.Column(db.String(50))    to_location_id = db.Column(db.Integer, db.ForeignKey('location.id'))    to_location = db.Column(db.String(50))    quantity = db.Column(db.Integer, nullable=False)    timestamp = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
查看完整描述

1 回答

?
慕标琳琳

TA贡献1830条经验 获得超9个赞

我发现出了什么问题,我没有在移动表中设置product_id 的值。


    if form.validate_on_submit():

        product = Product.query.filter_by(id=form.product.data).first()

        from_location = Location.query.filter_by(id=form.from_location.data).first()

        to_location = Location.query.filter_by(id=form.to_location.data).first()

        m = Movement(product_id = product.id, product = product.name, from_location_id = from_location.id, from_location = from_location.name, to_location_id = to_location.id, to_location = to_location.name, quantity = form.quantity.data)

        db.session.add(m)

        db.session.commit()

        movements = Movement.query.all()

        products = Product.query.all()

        locations = Location.query.all()

        return render_template('movements.html', movements=movements, products=products, locations=locations, form=form)

现在可以了。


查看完整回答
反对 回复 2023-08-22
  • 1 回答
  • 0 关注
  • 1394 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信