🎓 A1Learner
🔍
0 of 50 lessons completed

Updating and Deleting Objects

Updating an object changes a saved row. Deleting an object removes its row.

Save two posts

Two create calls save two posts. The snippets below change them.

Post.objects.create(title="First post", body="Hello from Django.")
Post.objects.create(title="Second post", body="Models save rows.")

Change a title

Get fetches the post. A new title is set, and save writes it back.

post = Post.objects.get(title="First post")
post.title = "New title"
post.save()
print(Post.objects.get(title="New title").body)

Update many rows at once

Filter finds the matching rows. Update changes the title on each one.

Post.objects.filter(title="Second post").update(title="Second post, revised")
print(Post.objects.filter(title="Second post, revised").count())

Delete a post

Get fetches the renamed post. Delete removes its row, so count drops to one.

post = Post.objects.get(title="New title")
post.delete()
print(Post.objects.count())

Example

import django
from django.conf import settings

settings.configure(
    DEBUG=True,
    SECRET_KEY="key",
    ROOT_URLCONF=__name__,
    ALLOWED_HOSTS=["*"],
    INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
    TEMPLATES=[{"BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [], "APP_DIRS": True}],
)
django.setup()

from django.db import connection, models

class Post(models.Model):
    title = models.CharField(max_length=100)
    body = models.TextField()

    class Meta:
        app_label = "blog"

with connection.schema_editor() as editor:
    editor.create_model(Post)

Post.objects.create(title="First post", body="Hello from Django.")
Post.objects.create(title="Second post", body="Models save rows.")
post = Post.objects.get(title="First post")
post.title = "New title"
post.save()
Post.objects.get(title="Second post").delete()
print(Post.objects.count())
print(Post.objects.get(title="New title").body)

Key points

  • Fetch the object first, then change a field on it.
  • Use .save() to write the changed object back to the database.
  • Use .delete() to remove a saved object from the database.
  • Use filter().update() to change every matching row at once.
  • Count after the change shows the rows that remain.

In this example, the setup lines configure Django. The program creates the table directly. A real project uses migrations for this step. Two create calls save two posts. Get fetches the first post, and a new title is set. Save writes the change back. The second post is fetched and deleted. Count prints 1, and the last print shows the body of the post that remains.

Note

Delete needs no save call, and the row is gone at once.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

How do you change a saved post's title?