185π
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:
38π
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)!
- [Django]-Http POST drops port in URL
- [Django]-IOS app with Django
- [Django]-How to force application version on AWS Elastic Beanstalk
29π
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
)
- [Django]-How to use subquery in django?
- [Django]-Http POST drops port in URL
- [Django]-Django: Record with max element
4π
Django has some documentation about that on their website, see: Saving changes to objects. To summarize:
.. to save changes to an object thatβs already in the database, use
save()
.
- [Django]-Django MEDIA_URL and MEDIA_ROOT
- [Django]-What is the purpose of adding to INSTALLED_APPS in Django?
- [Django]-How to delete a record in Django models?
4π
In my scenario, I want to update the status of status based on his id
student_obj = StudentStatus.objects.get(student_id=101)
student_obj.status= 'Enrolled'
student_obj.save()
Or If you want the last id from Student_Info table you can use the following.
student_obj = StudentStatus.objects.get(student_id=StudentInfo.objects.last().id)
student_obj.status= 'Enrolled'
student_obj.save()
- [Django]-How do I get user IP address in Django?
- [Django]-Execute code when Django starts ONCE only?
- [Django]-How to get getting base_url in django template