447
Use the queryset object update
method:
MyModel.objects.filter(pk=some_value).update(field1='some value')
129
Django database objects use the same save() method for creating and changing objects.
obj = Product.objects.get(pk=pk)
obj.name = "some_new_value"
obj.save()
How Django knows to UPDATE vs. INSERT
If the object’s primary key attribute is set to a value that evaluates to True (i.e., a value
other than None or the empty string), Django executes an UPDATE. If
the object’s primary key attribute is not set or if the UPDATE didn’t
update anything, Django executes an INSERT.
Ref.: https://docs.djangoproject.com/en/1.9/ref/models/instances/
- [Django]-Django/DRF – 405 Method not allowed on DELETE operation
- [Django]-Saving ModelForm error(User_Message could not be created because the data didn't validate)
- [Django]-What is "load url from future" in Django
32
This answer compares the above two approaches.
If you want to update many objects in a single line, go for:
# Approach 1
MyModel.objects.filter(field1='Computer').update(field2='cool')
Otherwise you would have to iterate over the query set and update individual objects:
#Approach 2
objects = MyModel.objects.filter(field1='Computer')
for obj in objects:
obj.field2 = 'cool'
obj.save()
-
Approach 1 is faster because, it makes only one database query, compared to approach 2 which makes ‘n+1’ database queries. (For n items in the query set)
-
Fist approach makes one db query ie UPDATE, the second one makes two: SELECT and then UPDATE.
-
The tradeoff is that, suppose you have any triggers, like updating
updated_on
or any such related fields, it will not be triggered on direct update ie approach 1. -
Approach 1 is used on a queryset, so it is possible to update multiple objects at once, not in the case of approach 2.
- [Django]-Django – SQL bulk get_or_create possible?
- [Django]-Django model one foreign key to many tables
- [Django]-ModuleNotFoundError: No module named 'grp' on windows
28
1st method
MyTable.objects.filter(pk=some_value).update(field1='some value')
2nd Method
q = MyModel.objects.get(pk=some_value)
q.field1 = 'some value'
q.save()
3rd method
By using get_object_or_404
q = get_object_or_404(MyModel,pk=some_value)
q.field1 = 'some value'
q.save()
4th Method
if you required if pk=some_value
exist then update
it other wise create
new one by using update_or_create
.
MyModel.objects.update_or_create(pk=some_value,defaults={'field1':'some value'})
- [Django]-How to change User representation in Django Admin when used as Foreign Key?
- [Django]-Django.contrib.gis.db.backends.postgis vs django.db.backends.postgresql_psycopg2
- [Django]-Whats the difference between using {{STATIC_URL}} and {% static %}
5
If you need to set the new value based on the old field value that is do something like:
update my_table set field_1 = field_1 + 1 where pk_field = some_value
use query expressions:
MyModel.objects.filter(pk=some_value).update(field1=F('field1') + 1)
This will execute update atomically that is using one update request to the database without reading it first.
- [Django]-How to get getting base_url in django template
- [Django]-How to submit form without refreshing page using Django, Ajax, jQuery?
- [Django]-Numeric for loop in Django templates
2
only in a case in serializer
things, you can update in very simple way!
my_model_serializer = MyModelSerializer(
instance=my_model, data=validated_data)
if my_model_serializer.is_valid():
my_model_serializer.save()
only in a case in form
things!
instance = get_object_or_404(MyModel, id=id)
form = MyForm(request.POST or None, instance=instance)
if form.is_valid():
form.save()
- [Django]-How to test "render to template" functions in django? (TDD)
- [Django]-Django model one foreign key to many tables
- [Django]-How do I clone a Django model instance object and save it to the database?
1
Accepted answer works great, but it comes with some unwanted side effect.
For example, you are using imageField, the update() will work and update others data, but not update your imageField data
class ProfileSetting(models.Model):
first_name = models.CharField(blank=True)
logo = models.ImageField(blank=True, null=True, upload_to="profile/logo/")
update_data = {
"first_name": "john",
"logo": request.FILES['logo'] # logo will not be properly update
}
ProfileSetting.objects.filter(pk=some_value).update(**update_data)
Here is some example with good explanation Django ImageField is not updating when update() method is used
- [Django]-Name '_' is not defined
- [Django]-Django proxy model and ForeignKey
- [Django]-Dynamically adding a form to a Django formset
0
Above mentioned answer works great, but it happens with some unwanted side effect, so to avoid such errors writes your db code inside exception blocks.
try:
obj = <Your_Model_Name>.objects.get(PK=<pk_id>)
obj.name = req.POST.get("name")
obj.save()
except Exception as e:
print(e)
- [Django]-Name '_' is not defined
- [Django]-Django: Fat models and skinny controllers?
- [Django]-How to resize an ImageField image before saving it in python Django model