简体   繁体   中英

SQL /peewee. How do I update a record based on condition from another table?

So I am trying to update a store after an item is bought. These are the models I'm working with.

class Cart():
    user = pw.ForeignKeyField(User, backref="cart_user", null=True)
    item = pw.ForeignKeyField(
        Item, backref="cart_item", null=True, on_delete='SET NULL')
    payment_status = pw.BooleanField(null=False, default=False)
    payment = pw.ForeignKeyField(Payment, backref="payment", null=True)
    amount = pw.IntegerField(null=False, default=1)

class Item():
    name = pw.CharField(null=False)
    product_type = pw.CharField(null=False)
    size = pw.CharField(null=False)
    color = pw.CharField(null=False, default=False)
    price = pw.IntegerField(null=False)
    image = pw.CharField(null=False)
    stock = pw.IntegerField(null=True)

After a buy, I would like the value of amount from cart be subtracted from the value of stock.

item = (Item.update(stock=20)
            .where(Item.id.in_
                   (Cart.select(Cart.item_id)
                    .where((Cart.user == current_id) & (Cart.payment_status == False)))))
    item.execute()

Ive gotten stuck here. I can only hard code the stock value. Im not sure how to subtract Cart.amount from Item.stock

ok finally found a solution

cart_amount = Cart.select(Cart.amount).where(Cart.item_id == Item.id)

        item = (Item.update(stock=Item.stock - cart_amount)
                .where(Item.id.in_
                       (Cart.select(Cart.item_id)
                        .where((Cart.user == current_id) & (Cart.payment_status == False)))))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM