Django 更新通过ForeignKey连接的模型

Django 更新通过ForeignKey连接的模型,django,django-models,Django,Django Models,嗨,我有通过foregin键连接的模型。我可以有多个订单,所以假设我有3个订单。2件衬衫1件裤子和4顶帽子。如何访问每个产品并根据订单数量更改其库存。 视图 order=order.objects.get\u或创建(customer=customer,complete=False) order\u items=OrderItem.objects.filter(order=order) 对于订单项目中的项目: item.product.stock=int(item.product.stock)-i

嗨,我有通过foregin键连接的模型。我可以有多个订单,所以假设我有3个订单。2件衬衫1件裤子和4顶帽子。如何访问每个产品并根据订单数量更改其库存。
视图

order=order.objects.get\u或创建(customer=customer,complete=False)
order\u items=OrderItem.objects.filter(order=order)
对于订单项目中的项目:
item.product.stock=int(item.product.stock)-int(item.quantity)
item.transaction\u id=事务\u id
item.save()
型号

类产品(models.Model):
title=models.CharField(最大长度=70,null=True,blank=True)
producent=models.CharField(最大长度=40,null=True,blank=True)
stock=models.PositiveIntegerField(null=True,blank=True)
类OrderItem(models.Model):
product=models.ForeignKey(product,on_delete=models.SET_NULL,blank=True,NULL=True)
quantity=models.IntegerField(默认值=0,null=True,blank=True)

您没有保存产品对象。试试这个:

for item in order_items:
    product = item.product
    product.stock = product.stock - item.quantity
    product.save()
    item.transaction_id = transaction_id
    item.save()