liveBook · Manning

Save()

As explained in Django in Action

save() is a Django method that persists a model instance, or a model instance produced by a ModelForm, to the database.

save() writes a Django model instance to the database. Changing an attribute changes only the in-memory Python object; calling save() synchronizes that change with the stored row. section 4.5

Use save() in two common ways:

  • Call it on an existing model instance after changing one or more attributes. section 4.5
  • Call it on a valid ModelForm, which saves and returns the corresponding model object. section 7.2.4 section 7.6
  • Use form.save(commit=False) when required model fields are not included in the form; assign them first, then save the instance. section 7.2.4

Updating a musician

dad = Musician.objects.get(id=4) dad.birth = date(1938, 2, 23) dad.save() The next query returns the updated birth date because save() sent the changed value to the database. section 4.5

Listing 7.10 View for displaying and submitting SeekingAdForm
# RiffMates/content/views.py
from django.contrib.auth.decorators import login_required
...
from content.forms import CommentForm, SeekingAdForm
from content.models import MusicianBandChoice, SeekingAd


@login_required  #1
def seeking_ad(request):
    if request.method == 'GET':
        form = SeekingAdForm()  #2

    else: # POST
        form = SeekingAdForm(request.POST)  #3

        if form.is_valid(): #4
            ad = form.save(commit=False)  #5
            ad.owner = request.user  #6
            ad.save()  #7

            return redirect("list_ads")  #8

    # Was a GET, or Form was not valid  #9
    data = {
        "form": form,
    }

    return render(request, "seeking_ad.html", data)

A form view validates submitted data, creates an unsaved ad with commit=False, assigns request.user to owner, saves it, and redirects to the listing. section 7.2.4

How Django in Action covers it

How deep it goes
Demonstrates in-memory changes, database synchronization, validation flow, and commit=False, but does not detail generated SQL.
Examples
Uses a musician birth-date correction and a classified-ad submission that assigns an owner before saving.
What it assumes
Assumes basic Python objects and attributes while introducing ORM instances, ModelForms, validation, and database persistence.
What you can do after
Apply it via the Django ORM or ModelForm to persist updates and prepare form-created objects before database storage.
How it connects
Connects model instances, Django ORM queries, ModelForm validation, redirects, and database persistence.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Django in Action. The section links point to the parts of the book it draws on.