How to update fields in a model without creating a new record in django?
Sometimes it may be required to execute the update atomically that is using one update request to the database without reading it first.
Also get
-set attribute
-save
may cause problems if such updates may be done concurrently or if you need to set the new value based on the old field value.
In such cases query expressions together with update
may by useful:
TemperatureData.objects.filter(id=1).update(value=F('value') + 1)
To update multiple fields:
TemperatureData.objects.filter(id=1).update(
value=F('value') + 1,
another_value=F('another_value')+1
)
You should do it this way ideally
t = TemperatureData.objects.get(id=1)
t.value = 999
t.save(['value'])
This allow you to specify which column should be saved and rest are left as they currently are in database. (https://code.djangoproject.com/ticket/4102)!
If you get a model instance from the database, then calling the save method will always update that instance. For example:
t = TemperatureData.objects.get(id=1)
t.value = 999 # change field
t.save() # this will update only
If your goal is prevent any INSERTs, then you can override the save
method, test if the primary key exists and raise an exception. See the following for more detail:
- How Django knows to UPDATE vs. INSERT