CRUD Operations

Back

Loading concept...

๐Ÿ—ƒ๏ธ Django Database Operations: CRUD Made Simple

The Story of the Magical Library ๐Ÿ“š

Imagine youโ€™re running a magical library. Every day, people come in to:

  • Add new books to the shelves (Create)
  • Find books they want to read (Read)
  • Change book information like fixing a typo (Update)
  • Remove old books nobody wants (Delete)

This is exactly what CRUD means! Itโ€™s the four things you do with data in any database.


๐ŸŽฏ What Youโ€™ll Master Today

โœ… Basic CRUD Methods - The four magic spells
โœ… Bulk Operations - Do many things at once
โœ… Get or Create Patterns - Smart shortcuts

๐Ÿ“– Part 1: Basic CRUD Methods

The Four Magic Spells

Think of your database like a toy box. You can:

Action What It Does Real Life Example
Create Put a new toy in Add a new friendโ€™s phone number
Read Find a toy Look up your friendโ€™s number
Update Fix a broken toy Change your friendโ€™s new number
Delete Remove an old toy Delete old contact

๐Ÿ†• CREATE - Adding New Things

The Simplest Way:

# Method 1: Create and save separately
book = Book(title="Harry Potter", author="J.K. Rowling")
book.save()

# Method 2: Create and save together (easier!)
book = Book.objects.create(
    title="Harry Potter",
    author="J.K. Rowling"
)

Whatโ€™s happening?

  • Book(...) = Make a new book (but itโ€™s not saved yet!)
  • .save() = Put it in the database
  • .create(...) = Make AND save in one step

๐Ÿ” READ - Finding Things

Get ONE specific thing:

# Find book with id=1
book = Book.objects.get(id=1)

# Find by name
book = Book.objects.get(title="Harry Potter")

Get MANY things:

# Get ALL books
all_books = Book.objects.all()

# Get books by one author
jk_books = Book.objects.filter(author="J.K. Rowling")

# Get first 5 books
first_five = Book.objects.all()[:5]
graph TD A["Want to find data?"] --> B{How many?} B -->|Just ONE| C["use .get"] B -->|MANY or ALL| D["use .filter or .all"] C --> E["Returns ONE object"] D --> F["Returns a list"]

โœ๏ธ UPDATE - Changing Things

Change ONE thing:

# Step 1: Find the book
book = Book.objects.get(id=1)

# Step 2: Change it
book.title = "Harry Potter and the Sorcerer's Stone"

# Step 3: Save the change
book.save()

Change MANY things at once:

# Make all books by "Unknown" have a new author
Book.objects.filter(author="Unknown").update(
    author="Anonymous"
)

๐Ÿ—‘๏ธ DELETE - Removing Things

Remove ONE thing:

# Find it first
book = Book.objects.get(id=1)

# Delete it
book.delete()

Remove MANY things:

# Delete all books by one author
Book.objects.filter(author="Old Author").delete()

# โš ๏ธ Be careful! This deletes ALL books!
Book.objects.all().delete()

๐Ÿ“– Part 2: Bulk Operations

Why Bulk Operations?

Imagine you have 1000 new books to add. You could:

โŒ Slow Way: Add one book, wait, add another, waitโ€ฆ (1000 trips to database!)

โœ… Fast Way: Put all 1000 books in a truck and deliver once!


๐Ÿš€ bulk_create - Add Many at Once

# Create a list of books
new_books = [
    Book(title="Book 1", author="Author A"),
    Book(title="Book 2", author="Author B"),
    Book(title="Book 3", author="Author C"),
]

# Add all at once - ONE database trip!
Book.objects.bulk_create(new_books)

Pro tip: For huge lists, use batches:

Book.objects.bulk_create(new_books, batch_size=100)

โšก bulk_update - Change Many at Once

# Get books to update
books = Book.objects.filter(author="Old Name")

# Change each one
for book in books:
    book.author = "New Name"

# Save all changes at once!
Book.objects.bulk_update(books, ['author'])

The ['author'] tells Django which fields changed.


๐Ÿ“Š Bulk Operations Comparison

graph LR A["Need to save 1000 items"] --> B{Which method?} B -->|One by one| C["1000 database calls ๐ŸŒ"] B -->|bulk_create| D["1 database call ๐Ÿš€"]
Method When to Use Speed
save() loop Few items Slow
bulk_create() Many new items Fast!
bulk_update() Many changes Fast!

๐Ÿ“– Part 3: Get or Create Patterns

The Smart Shortcut

Have you ever tried to add a friend whoโ€™s already in your contacts?

Django has a smart way to handle this:

  • If it exists โ†’ just get it
  • If it doesnโ€™t exist โ†’ create it

๐ŸŽฏ get_or_create - The Basic Pattern

# Try to find or create an author
author, created = Author.objects.get_or_create(
    name="J.K. Rowling"
)

# 'created' tells you what happened
if created:
    print("New author added!")
else:
    print("Author already existed!")

What you get back:

  • author = the object (new or existing)
  • created = True (new) or False (already existed)

๐Ÿ› ๏ธ Adding Extra Data

What if you find nothing and need to create with more info?

author, created = Author.objects.get_or_create(
    name="J.K. Rowling",
    defaults={
        "country": "UK",
        "birth_year": 1965
    }
)

How it works:

  • Searches by name="J.K. Rowling"
  • If not found: creates with name + all defaults
  • defaults are ONLY used when creating

๐Ÿ”„ update_or_create - Create OR Update

Sometimes you want to:

  • Create if not exists
  • Update if it does exist
author, created = Author.objects.update_or_create(
    name="J.K. Rowling",
    defaults={
        "latest_book": "The Ickabog",
        "is_active": True
    }
)

The magic:

  • Found? โ†’ Updates with defaults
  • Not found? โ†’ Creates with defaults

๐Ÿค” Which Pattern to Use?

graph TD A["What do you need?"] --> B{Already exists?} B -->|Don't care, just get it| C["get_or_create"] B -->|Want to update it| D["update_or_create"] C --> E["Returns existing OR creates new"] D --> F["Creates new OR updates existing"]
Pattern Creates? Updates? Best For
get_or_create โœ… โŒ Add only if missing
update_or_create โœ… โœ… Always stay current

๐ŸŽ‰ Quick Summary

Your New Superpowers:

Basic CRUD:

  • ๐Ÿ†• .create() - Add new stuff
  • ๐Ÿ” .get() / .filter() - Find stuff
  • โœ๏ธ .save() / .update() - Change stuff
  • ๐Ÿ—‘๏ธ .delete() - Remove stuff

Bulk Operations:

  • ๐Ÿš€ bulk_create() - Add many fast
  • โšก bulk_update() - Change many fast

Smart Patterns:

  • ๐ŸŽฏ get_or_create() - Get or make new
  • ๐Ÿ”„ update_or_create() - Get and update or make new

๐Ÿ’ก Golden Rules

  1. Use .create() instead of save() for new objects - itโ€™s cleaner!

  2. Use .get() when you expect exactly ONE result

    • It throws an error if 0 or 2+ results!
  3. Use bulk operations for 10+ items - your database will thank you!

  4. Use get_or_create to avoid duplicates - no more โ€œalready existsโ€ errors!


๐ŸŒŸ Remember: Every app you use - Instagram, WhatsApp, games - they all do these same four things: Create, Read, Update, Delete. Now you know how too!

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.