Django update Data

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.