← Back to Django, page 3

django-0051 · Easy fresher

How do you create, read, update and delete rows with the Django ORM, and what do get_or_create() and update_or_create() return?

Create with Model.objects.create() or instance.save(), read with get() for exactly one row or filter() for many, update with save() on an instance or update() on a queryset, and delete with delete(). get_or_create() and update_or_create() return a tuple of (object, created) so the caller knows whether a row was inserted.

Full answer

CRUD maps to four groups of ORM calls.

Create: Student.objects.create(name="Asha") inserts immediately. Alternatively build Student(name="Asha") and call .save().

Read: get() returns one object and raises DoesNotExist if nothing matches or MultipleObjectsReturned if more than one does. filter() returns a lazy QuerySet that may hold zero, one or many rows. first() and last() return an object or None.

Update: change attributes and call save() (writes every column unless update_fields is given), or run Student.objects.filter(...).update(grade="A"), which issues one UPDATE statement, skips save() and signals, and returns the number of rows changed.

Delete: instance.delete() or queryset.delete(). Both return (total_deleted, {label: count}), including cascaded rows.

get_or_create(defaults=..., **lookup) looks up by the keyword arguments, and creates the row with the lookup values plus defaults if none exists. update_or_create() does the same but applies defaults as updates when the row exists. Both return (obj, created). They are safe against races only when the lookup fields are backed by a unique constraint; otherwise two requests can both insert, and a later get() raises MultipleObjectsReturned.

Do not call get() for something that might not exist without handling DoesNotExist, or use filter(...).first().

python
import sys
import types

import django
from django.conf import settings

# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__

settings.configure(
    SECRET_KEY="demo-only-key-not-for-production",
    ALLOWED_HOSTS=["testserver"],  # the host name used by Django's test client
    INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()

from django.db import models, connection


class Student(models.Model):
    roll_no = models.CharField(max_length=10, unique=True)
    name = models.CharField(max_length=40)
    grade = models.CharField(max_length=2, default="C")

    class Meta:
        app_label = "school"


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

asha = Student.objects.create(roll_no="BCA-1", name="Asha")
Student(roll_no="BCA-2", name="Ravi").save()
print(Student.objects.get(roll_no="BCA-1").name)

try:
    Student.objects.get(roll_no="BCA-9")
except Student.DoesNotExist:
    print("no such student")

asha.grade = "A"
asha.save(update_fields=["grade"])
print(Student.objects.filter(grade="C").update(grade="B"), "row updated in one query")

obj, created = Student.objects.get_or_create(roll_no="BCA-3", defaults={"name": "Kiran"})
print(obj.name, created)
obj, created = Student.objects.get_or_create(roll_no="BCA-3", defaults={"name": "Other"})
print(obj.name, created)
obj, created = Student.objects.update_or_create(roll_no="BCA-3", defaults={"grade": "A"})
print(obj.grade, created)
print(Student.objects.filter(grade="A").delete())

Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): Asha no such student 1 row updated in one query Kiran True Kiran False A False (2, {'school.Student': 2})

Key points

  • create() inserts; get() expects exactly one row
  • update() on a queryset is one SQL statement and skips save() and signals
  • delete() returns the number of rows removed, cascades included
  • get_or_create returns (obj, created); needs a unique constraint to be race-safe

Common mistakes

  • Calling get() when zero or several rows are possible without handling the exceptions
  • Using get_or_create on fields that are not unique
  • Expecting update() to call save() or send signals
  • Forgetting that queryset.delete() cascades to related rows

Follow-ups

  • How would you make get_or_create safe under concurrent requests?
  • What does save(update_fields=[...]) change in the SQL?
  • How does bulk_create differ from calling create() in a loop?

Tips

  • State which exceptions get() raises
  • Mention the (obj, created) tuple
  • Name the unique-constraint requirement