如何更新外国钥匙值django
假设我有以下型号(模型
class stockList(models.Model):
product_name = models.CharField(max_length=255, null=True, unique=True)
product_image = models.ImageField(upload_to='photos')
product_type = models.CharField(max_length=50, null=True)
product_description = models.TextField(null=True)
quantity_in_store = models.IntegerField(null=True)
location = models.CharField(max_length=50, null=True)
class stockOut(models.Model):
staff_name = models.ForeignKey("staff", on_delete=models.CASCADE, null=True)
stock = models.ForeignKey("stockList", on_delete=models.CASCADE, null=True)
shipping_qty = models.IntegerField(null=True)
shipping_company = models.CharField(max_length=255, null=True)
。获取最终数量,但我想将最终数量的价值更新到dentity_in_store(来自StockList模型),我该如何执行此操作
?
class stockout(admin.ModelAdmin):
list_display = ["staff_name", "stock", "shipping_qty", "shipping_company"]
def save_model(self, request, obj, form, change):
stock = obj.stock
shipping_qty = obj.shipping_qty
if shipping_qty and stock.quantity_in_store:
obj.stock.quantity_in_store = stock.quantity_in_store - shipping_qty
super().save_model(request, obj, form, change)
Let say I have following models (models.py):
class stockList(models.Model):
product_name = models.CharField(max_length=255, null=True, unique=True)
product_image = models.ImageField(upload_to='photos')
product_type = models.CharField(max_length=50, null=True)
product_description = models.TextField(null=True)
quantity_in_store = models.IntegerField(null=True)
location = models.CharField(max_length=50, null=True)
class stockOut(models.Model):
staff_name = models.ForeignKey("staff", on_delete=models.CASCADE, null=True)
stock = models.ForeignKey("stockList", on_delete=models.CASCADE, null=True)
shipping_qty = models.IntegerField(null=True)
shipping_company = models.CharField(max_length=255, null=True)
First of all I have to do a subtraction between quantity_in_store (from stockList models) and shipping_qty(from stockout models) and to get the final quantity that left in store. However, I have get the final quantity but I would like to update the value of final quantity into the quantity_in_store(from stockList models) How would I go about doing this? Thanks
admin models:
class stockout(admin.ModelAdmin):
list_display = ["staff_name", "stock", "shipping_qty", "shipping_company"]
def save_model(self, request, obj, form, change):
stock = obj.stock
shipping_qty = obj.shipping_qty
if shipping_qty and stock.quantity_in_store:
obj.stock.quantity_in_store = stock.quantity_in_store - shipping_qty
super().save_model(request, obj, form, change)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尽管保存的检查数量是一种不好的做法,但应该在验证时完成,您可以使用您的代码:
Although check quantity on save is a bad practice, it should be done on validation, you can use your code: