2017-07-04 77 views
0

我有以下型號和協會:刪除所有在一個多對多的輔助表關聯在SQLAlchemy的

class CartProductsAssociation(db.Model): 
    __tablename__ = 'cart_products_association' 
    cart_id = db.Column(db.Integer, db.ForeignKey('carts.id',ondelete='CASCADE'),primary_key=True) 
    product_id = db.Column(db.Integer, db.ForeignKey('products.id',ondelete='CASCADE'), primary_key=True) 
    quantity = db.Column(db.Integer) 

    product = db.relationship("Product", backref="cart_associations", cascade="all,delete",passive_deletes=True) 
    cart = db.relationship("Cart", backref="product_associations",cascade="all,delete",passive_deletes=True) 


class Product(db.Model): 
    __tablename__ = 'products' 
    id = db.Column(db.Integer, primary_key=True) 
    name = db.Column(db.String) 
    img_path = db.Column(db.String) 

    price = db.Column(db.Float, default=0.0) 

    product_categories = db.relationship(
     "ProductCategory", 
     secondary=product_product_categories, 
     back_populates="products") 

    carts = db.relationship("Product", secondary="cart_products_association",passive_deletes=True,cascade="all,delete") 

class Cart(db.Model): 
    __tablename__ = 'carts' 
    id = db.Column(db.Integer, primary_key=True) 

    branch_id = db.Column(db.Integer, db.ForeignKey('branch.id')) 
    branch = db.relationship("Branch", back_populates="carts") 

    page_id = db.Column(db.Integer, db.ForeignKey('pages.id')) 
    page = db.relationship("Page", back_populates="carts") 


    shopper_id = db.Column(db.String, db.ForeignKey('shoppers.fb_user_id')) 
    shopper = db.relationship(
     "Shopper", 
     back_populates="carts") 

    products = db.relationship("Product", secondary="cart_products_association") 
    cart_status = db.Column(db.Enum('user_unconfirmed','user_confirmed','client_unconfirmed','client_confirmed', name='cart_status'), default='user_unconfirmed') 

當我試圖刪除產品我收到以下錯誤: Asse田

AssertionError: Dependency rule tried to blank-out primary key column 'cart_products_association.cart_id' on instance '<CartProductsAssociation at 0x7f5fd41721d0>' 

我該如何解決?

+1

的可能的複製[相關規則試圖空出主鍵SQLAlchemy中,當外鍵約束是複合主鍵的一部分(https://stackoverflow.com/問題/ 23699651 /依賴規則,試圖對空出,主鍵功能於SQLAlchemy的-時,外鍵-C) –

回答

0

它解決了這個問題:

product = models.Product.query.get(product_id) 

for ass in product.cart_associations: 

    db.session.delete(ass) 

db.session.delete(product) 
db.session.commit() 
相關問題