如何在Django中更新相关模型字段

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

我有两种模型(购买和库存),我要在购买商品时更新库存中的数量字段。 (例如,我有2个芒果库存,我购买了3个芒果,我希望更新的库存为5个芒果)

我的模特

class Stock(models.Model):
    product = models.ForeignKey(Products, null=True, blank=True, on_delete = models.SET_NULL)
    stock_date = models.DateField(null=True, blank=True)
    quantity = models.DecimalField(max_digits = 10, decimal_places = 2, blank=True)
    buying_price = models.DecimalField(max_digits = 10, decimal_places = 2, blank=True)

class Purchase(models.Model):
    product = models.ForeignKey(Stock, null=True, blank=True, on_delete = models.SET_NULL)
    order_date = models.DateField(null=True, blank=True)
    quantity = models.DecimalField(max_digits = 10, decimal_places = 2, blank=True)
    buying_price = models.DecimalField(max_digits = 10, decimal_places = 2, blank=True)

任何人都可以帮忙!

python django django-models
2个回答
0
投票

您可以像访问任何变量一样访问Django模型

 CurrentPurchase.stock.quantity = 5

或您可以使用过滤器获取所需的对象:

Model.objects.filter(AnotherModel=Model_)

0
投票

您应该使用Django Signals。

从django.db.models.signals导入post_save

def update_stock(sender, instance, **kwargs):
    product = instance.product.id    
    stock = Stock.objects.get(product=product.id)
    stock.quantity = stock.quantity + instance.quantity

post_save.connect(update_stock, sender=Purchase)

您可以根据需要添加例外。

© www.soinside.com 2019 - 2024. All rights reserved.