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.
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.title02 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.
python manage.py makemigrations core
python manage.py migrate
python manage.py shell03 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.
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.
note.body = "Create, retrieve, update, repeat."
note.save(update_fields=["body"])
Note.objects.count()Read the official Django documentation for details and more examples.