1

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?

1 Answer 1

2

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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.