My models:
class InventoryItem(models.Model):
quantity = models.IntegerField()
...
class Requisition(models.Model):
from_inventoryitem = models.ForeignKey(InventoryItem)
quantity = models.IntegerField()
...
Assuming that requisition has an OneToMany relation with inventory_item below, and the initial value of inventory_item.quantity is 0, When I excute:
>>> requisition = Requisition.objects.get(id=1)
>>> requisition.from_inventoryitem.quantity = 500
>>> requisition.save()
>>> requisition.from_inventoryitem.quantity
500
>>> inventory_item.quantity
0
>>> requisition.from_inventoryitem == inventory_item
True
The inventory_item.quantity in database and InventoryItem side is still 0. How can I update that change to the database?
This is by design. You have to save each instance seperately. requisition.from_inventoryitem
actually queries the InventoryItem instance from the database, just to set the quantity.
requisition = Requisition.objects.get(id=1)
requisition.from_inventoryitem.quantity = 500 # this generates another query here!
requisition.from_inventoryitem.save()
or even better, with a single query, single save
inv_item = InventoryItem.objects.get(requisition_set__id=1)
inv_item.quantity = 500
inv_item.save()
best way. single database call:
InventoryItem.objects.filter(requisition_set__id=1).update(quantity=500)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments