In Django, updating data in the database involves modifying existing records in a table. This can be done using the Django ORM methods like save(), update(), or filtering records and updating them.
Update a Single Record
You retrieve the record, modify its fields, and call .save().
Example:
from myapp.models import Book # Replace 'myapp' with your app name
# Retrieve a book by its ID (or any other filter condition)
book = Book.objects.get(id=1)
# Modify the fields
book.title = "Updated Title"
book.author = "Updated Author"
# Save the changes to the database
book.save()
Explanation:
- get(id=1) retrieves the book with the primary key 1.
- Fields title and author are updated.
- The .save() method writes the changes back to the database.
Update Multiple Records
If you want to update multiple records at once, use the .filter() method combined with .update().
Example:
from myapp.models import Book
# Update all books published before 2000
Book.objects.filter(published_year__lt=2000).update(author="New Author")
Explanation:
1. filter(published_year__lt=2000) selects books published before the year 2000.
2. update(author=”New Author”) changes the author field for all matching records.
Updating multiple Data through bulk_update
If you need to update multiple objects’ fields at once:
from django.db import models
from myapp.models import Book
# Get all books with the 'Unknown' author
books = Book.objects.filter(author="Unknown")
# Modify the records in memory
for book in books:
book.published_year = 2023
# Bulk update the `published_year` field for all books
Book.objects.bulk_update(books, ['published_year'])
Updating multiple Data through save()
For bulk updates (updating multiple fields of multiple records efficiently), Django requires iterating through each record and calling .save():
books = Book.objects.filter(author="Unknown") # Fetch books with 'Unknown' author
# Update each book
for book in books:
book.published_year = 2023 # Update field
book.save() # Save changes
Summary
Use get() and .save() to update a single record.
Use filter() and .update() for conditional or bulk updates.
Use bulk_update() for efficiently updating specific fields of many records.
Django update Data – Interview Questions
Q 1: How do you update records in Django?
Q 2: What does update() do?
Q 3: Can forms update data?
Q 4: What is get() used for?
Q 5: Is update() faster than save()?
Django update Data – Objective Questions (MCQs)
Q1. Updating a record in Django is done using:
Q2. To fetch an item before updating, which method is used?
Q3. After modifying an object, you must call:
Q4. Which of the following updates multiple rows at once?
Q5. The update() method is called on: