简体   繁体   English

如何更新 Django 中的相关 model 字段

[英]How to update related model fields in Django

I have two models (purchase and stock), I Want when i purchase an item the quantity field in stock to be updated.我有两种型号(购买和库存),我希望在购买商品时更新库存中的数量字段。 (eg. i have 2 Mangoes in stock and i purchase 3 Mongoes, i want the updated stock to be 5 Mangoes) (例如,我有 2 个芒果库存,我购买了 3 个芒果,我希望更新后的库存为 5 个芒果)

My Models我的模特

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)

Can anyone help please!任何人都可以帮忙吗!

You can access Django models like any variable您可以像访问任何变量一样访问 Django 模型

 CurrentPurchase.stock.quantity = 5

or you can use filter to get the object you want:或者您可以使用过滤器来获取您想要的 object:

Model.objects.filter(AnotherModel=Model_)

You should use Django Signals.您应该使用 Django 信号。

from django.db.models.signals import post_save从 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)

You can add the exceptions according to your needs.您可以根据需要添加例外。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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