Let’s say we want to update an object, we can simply change the object attributes and then save them
from django.shortcuts import renderfrom store.models import Collection
def say_hello(request): '''note that all the below fields are updated ones''' collection = Collection(pk=11) collection.title = "Games" collection.featured_product = None collection.save() passNow the problem with the above approach is that, it updates all the fields in the database. So what if you want to only update certain fields, like for instance you want to update just the featured product. You can do something like below
from django.shortcuts import renderfrom store.models import Collection
def say_hello(request): collection = Collection(pk=11) collection.featured_product = 'Test' collection.save() passTechnically, its supposed to work since we are only updating the featured product field, but what happens is that when you check the sql queries in the debug toolbar, it will set the title field to an empty string "". This is because the title that is being stored in memory is an empty string, since we didnt do anything to it. We just updated the featured product field. So we have lost the title as well.
To fix this, we have to read the data from the database and then do the partial update. see below
def say_hello(request): collection = collection.objects.get(pk=11) #reads all values in the collection '''then we can go ahead and do our partial update''' collection.featured_product = 'Update' collection.save() passThe above implementation can cause performance issues since it always reads before it update, tho it rarely happens. But if it does, there is a similar method to the ‘create’ called ‘update’ that we can use to update the field directly. provided we give it the keyword arguments
Collection.objects.update(featured_product='Update')The above implementation, will update the featured product values for all fields in the collection table. So we have to filter it by the exact featured product value we want to update and then update it.
Collection.objects.filter(pk=11).update(featured_product='Update')