Creating & Reading Records

Use the model manager to insert and fetch rows.

SyntaxPost.objects.create(...) / Post.objects.filter(...)

Every model has an objects manager that is your gateway to the database. Use it to create and query records without writing SQL.

  • Model.objects.create(**fields) — insert a row.
  • Model.objects.all() — every row.
  • Model.objects.get(pk=1) — a single row (raises if not found).
  • Model.objects.filter(...) — rows matching a condition.

Example

Example Β· python
from blog.models import Post

# Create
post = Post.objects.create(title="Hello", body="World")

# Read
all_posts = Post.objects.all()
one = Post.objects.get(pk=1)
published = Post.objects.filter(published=True)

# Save changes on an instance
post.title = "Updated"
post.save()

When to use it

  • A developer uses Post.objects.create() to insert a new record in a single line of Python.
  • A developer calls .filter().update() to bulk-update all published posts' status in one database query.
  • An admin script uses .delete() to remove all expired session records from the database.

More examples

Create and retrieve objects

Shows the three basic ORM operations: create(), all(), and get() for single-object retrieval.

Example Β· python
from .models import Post

# Create
post = Post.objects.create(title="Hello", body="World")

# Retrieve all
all_posts = Post.objects.all()

# Retrieve one
post = Post.objects.get(pk=1)

Update an object

Demonstrates updating a single record via save() and bulk-updating multiple records with update().

Example Β· python
# Update a single instance
post = Post.objects.get(pk=1)
post.title = "Updated Title"
post.save()

# Bulk update
Post.objects.filter(draft=True).update(draft=False)

Delete objects

Deletes a single record or bulk-deletes multiple records that match a filter condition.

Example Β· python
# Delete a single object
post = Post.objects.get(pk=1)
post.delete()

# Bulk delete
Post.objects.filter(published_at__isnull=True).delete()

Discussion

  • Be the first to comment on this lesson.
Creating & Reading Records β€” Django | SoundsCode