About Lesson
1. Creating Records
Add new rows to the database:
book = Book(
title="Django for Beginners",
author="John Doe",
publication_date="2024-01-01",
isbn="1234567890123",
available=True
)
book.save() # Save to the database
Shortcut:
Book.objects.create(
title="Learn Django",
author="Jane Doe",
publication_date="2023-12-01",
isbn="9876543210987",
available=True
)
2. Reading Records
Retrieve data from the database:
# Get all records
books = Book.objects.all()
# Get a specific record
book = Book.objects.get(id=1)
# Filter records
available_books = Book.objects.filter(available=True)
# Exclude records
unavailable_books = Book.objects.exclude(available=True)
# Ordering
books = Book.objects.order_by('-publication_date')
3. Updating Records
Modify existing data:
book = Book.objects.get(id=1)
book.title = "Advanced Django"
book.save()
4. Deleting Records
Remove data from the database:
book = Book.objects.get(id=1)
book.delete()
Join the conversation