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

我试图从产品表中删除产品,同时也从产品移动表中删除该产品的所有移动(称为移动),但仅删除产品,而不删除其移动。有谁知道为什么?这是代码:


@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)


皈依舞
浏览 1409回答 1
1回答

慕标琳琳

我发现出了什么问题,我没有在移动表中设置product_id 的值。&nbsp; &nbsp; if form.validate_on_submit():&nbsp; &nbsp; &nbsp; &nbsp; product = Product.query.filter_by(id=form.product.data).first()&nbsp; &nbsp; &nbsp; &nbsp; from_location = Location.query.filter_by(id=form.from_location.data).first()&nbsp; &nbsp; &nbsp; &nbsp; to_location = Location.query.filter_by(id=form.to_location.data).first()&nbsp; &nbsp; &nbsp; &nbsp; 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)&nbsp; &nbsp; &nbsp; &nbsp; db.session.add(m)&nbsp; &nbsp; &nbsp; &nbsp; db.session.commit()&nbsp; &nbsp; &nbsp; &nbsp; movements = Movement.query.all()&nbsp; &nbsp; &nbsp; &nbsp; products = Product.query.all()&nbsp; &nbsp; &nbsp; &nbsp; locations = Location.query.all()&nbsp; &nbsp; &nbsp; &nbsp; return render_template('movements.html', movements=movements, products=products, locations=locations, form=form)现在可以了。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python