Django 6 cheatsheet
Django 6: ORM queries
8 common Django 6 tasks.
Create a row
Insert a new object into the database.
Post.objects.create(title="Hello", body="First post")
Get one object
Fetch a single object. It raises DoesNotExist or MultipleObjectsReturned otherwise.
Post.objects.get(pk=1)
Filter and sort
Get published posts, newest first.
Post.objects.filter(published=True).order_by("-created")
Search with a lookup
Find posts whose title contains a word, ignoring case.
Post.objects.filter(title__icontains="django")
Update many rows
Update all matching rows with one query.
Post.objects.filter(published=False).update(published=True)
Delete rows
Delete all matching rows.
Post.objects.filter(published=False).delete()
Caution: Deletes immediately and can cascade to related rows.
Avoid N+1 queries
Fetch a foreign key in the same query. Use prefetch_related for many-to-many and reverse relations.
Post.objects.select_related("author")
Count related objects
Add a count of comments to each post.
from django.db.models import Count
Post.objects.annotate(n_comments=Count("comments"))