← All tutorials

Database / 8 MIN READ

Save and query data with the Django ORM

Define a Note model, create its database table, and practice everyday QuerySet operations.

01 Define the data

Use a project with core installed and the default SQLite database. Add this model to core/models.py. A model describes the fields Django will store in a database table.

Code example
from django.db import models


class Note(models.Model):
    title = models.CharField(max_length=200)
    body = models.TextField(blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.title

02 Create the table

For this tutorial project, generate a migration and apply it. Read the generated file before applying it to understand the schema change. Commit migration files along with your model changes.

Code example
python manage.py makemigrations core
python manage.py migrate
python manage.py shell

03 Create and retrieve notes

Run these Python statements in the Django shell. create() saves immediately; filter() returns a QuerySet that can be refined before the database query is evaluated.

Code example
from core.models import Note

note = Note.objects.create(title="Learn the ORM", body="Start small.")
Note.objects.get(pk=note.pk)
list(Note.objects.filter(title__icontains="orm").order_by("-created_at"))

04 Update and inspect

Change a field and save only that field. QuerySet.count() asks the database for the number of matching rows. Use exit() to leave the shell when you are finished.

Code example
note.body = "Create, retrieve, update, repeat."
note.save(update_fields=["body"])
Note.objects.count()
Keep exploring

Read the official Django documentation for details and more examples.