sandeep
sandeep

Reputation: 711

save() not updating the table in database

I have to update 2 tables in database every time user visit a page.

this is working:

order_order = OrderTable.no_objects.get(order_number=order_id)

order_order.status = 'updated status'
order_order.save()

This is not working: (related with first table through foreign key)

order_item = ItemsTable.objects.filter(order_id__order_number=order_id)
for i in range(order_item.count()):
        order_item[i].qty = i + 5
        order_item[i].qty_nextMonth = i + 30
        order_item[i].save()

Can anyone tell what's wrong in 2nd part of code. It's not updating the database.

Upvotes: 2

Views: 311

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477794

Each time you write order_item[i], you make a separate fetch, and you return an ItemsTable item from the database. That means that if you set the .qty = ... attribute of that object, it is simply ignored, since the next order_item[i] will trigger a new fetch. Your order_item[i].save() updates the record in the database, but with the values that have been retrieved just from a fetch from the database.

It is better to simply iterate over the queryset, and thus maintain a reference to the same ItemsTable object:

order_items = ItemsTable.objects.filter(order_id__order_number=order_id)
for i, order_item in enumerate(order_items):
        order_item.qty = i + 5
        order_item.qty_nextMonth = i + 30
        order_item.save()

This is more efficient as well, since enumerating over a queryset forces evaluation, and hence you fetch all objects at once.

As of , you can use .bulk_update(..) [Django-doc], to update in bulk an iterable of objects.

Upvotes: 2

Related Questions