Reading Objects in Django
Reading objects fetches rows from the database. A QuerySet holds the matching rows.
Save two posts
Two create calls save two posts. The snippets below read them back.
Post.objects.create(title="First post", body="Hello from Django.")
Post.objects.create(title="Second post", body="Models save rows.")Fetch every post
All returns every saved post. The loop prints each title.
for post in Post.objects.all().order_by("title"):
print(post.title)Keep the matching posts
Filter keeps only posts with the given title. Count shows one match.
print(Post.objects.filter(title="Second post").count())Fetch one post
Get returns the single matching post. Its body prints next.
print(Post.objects.get(title="First post").body)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.objects.create(title="Third post", body="Reading finds rows.")
print(Post.objects.count())
for post in Post.objects.all().order_by("title"):
print(post.title)
print(Post.objects.filter(title="Second post").count())
print(Post.objects.get(title="First post").body)
Key points
- Post.objects.all() returns a QuerySet with every post.
- Use .filter() to keep only the rows that match a value.
- Use .get() to fetch the one row that matches a value.
- A QuerySet prints in a loop, one row at a time.
- Use .order_by() to fix the order of the rows.
In this example, the setup lines configure Django. The program creates the table directly. A real project uses migrations for this step. Three create calls save three posts. Count prints 3. The loop prints the three titles in order. Filter counts the posts titled Second post, so it prints 1. Get fetches the first post and prints its body.
Note
Filter returns an empty QuerySet when nothing matches, not an error.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which call fetches the one post titled First post?