Does django's `save()` create or update?

Question:

The documentation just says

To save an object back to the database, call save()

That does not make it clear. Exprimenting, I found that if I include an id, it updates existing entry, while, if I don’t, it creates a new row. Does the documentation specify what happens?

Asked By: blue_note

||

Answers:

Depends on how the Model object was created. If it was queried from the database, UPDATE. If it’s a new object and has not been saved before, INSERT.

Answered By: Freek Wiekmeijer

It’s fuly documented here:

https://docs.djangoproject.com/en/2.2/ref/models/instances/#how-django-knows-to-update-vs-insert

You may have noticed Django database objects use the same save()
method for creating and changing objects. Django abstracts the need to
use INSERT or UPDATE SQL statements. Specifically, when you call
save(), Django follows this algorithm:

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 (e.g. if primary key is set to
a value that doesn’t exist in the database), Django executes an
INSERT. The one gotcha here is that you should be careful not to
specify a primary-key value explicitly when saving new objects, if you
cannot guarantee the primary-key value is unused. For more on this
nuance, see Explicitly specifying auto-primary-key values above and
Forcing an INSERT or UPDATE below.

As a side note: django is OSS so when in doubt you can always read the source code 😉

Answered By: bruno desthuilliers

This is Old, but I don’t think it was answered.

when you call update() or create(), you don’t need to call save() again after the fact, except if you change something else after the update call.
https://docs.djangoproject.com/en/4.2/ref/models/instances/.

Django basically uses the same algorithm from update() and create() in save(), so they all effect the changes directly on the Database.

Answered By: Leodarkseid
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.