SQL / peewee。如何根据另一个表中的条件更新记录?

问题描述 投票:0回答:1

因此,我正在尝试在购买商品后更新商店。这些是我正在使用的模型。

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)

购买后,我希望从购物车的价值中减去购物车中的价值。

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

我被困在这里。我只能对股票价值进行硬编码。我不确定如何从Item.stock中减去Cart.amount

python sql peewee flask-peewee
1个回答
0
投票

确定终于找到了解决方案

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)))))
© www.soinside.com 2019 - 2024. All rights reserved.