Home » Django » Django update object

Django update object

Posted by: admin November 30, 2017 Leave a comment

Questions:

How do I run an update and select statement on the same queryset rather than having to do two queries, one to select the object and one to update the object?

The equivalent in SQL would be something like:

update my_table set field_1 = 'some value' where pk_field = some_value
Answers:

Use the queryset object update method:

MyModel.objects.filter(pk=some_value).update(field1='some value')

Questions:
Answers:

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/