3️⃣ 🗃️ Django Data Management
Estimated reading: 3 minutes 106 views

🔄 Django Update Data – Modify Existing Records in the Database (2025 Guide)

🧲 Introduction – Why Learn to Update Data in Django?

In Django, updating data refers to modifying existing rows in your database using Django’s powerful ORM. Whether from a form, view, or admin panel, updating allows you to keep your site’s content accurate and current.

🎯 In this guide, you’ll learn:

  • How to update records using Django shell
  • How to update data via views
  • How to use save() and update() correctly
  • Best practices for safe updates

🛠️ Step 1: Sample Model for Update

models.py

from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=200)
    content = models.TextField()
    published = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.title

🧪 Step 2: Update Using Django Shell

$ python manage.py shell

Then:

from blog.models import Post
post = Post.objects.get(id=1)
post.title = "Updated Title"
post.content = "Updated content here."
post.save()

✅ This modifies and saves the record with ID 1.


🌐 Step 3: Update Data in a View

views.py

from django.shortcuts import get_object_or_404
from django.http import HttpResponse
from .models import Post

def update_post(request, post_id):
    post = get_object_or_404(Post, id=post_id)
    post.title = "View-Based Update"
    post.save()
    return HttpResponse("✅ Post Updated")

Map to URL:

urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('update/<int:post_id>/', views.update_post, name='update-post'),
]

Visit http://localhost:8000/update/1/ to update the post.


📦 Step 4: Use .update() for Bulk or QuerySet Updates

Post.objects.filter(id=1).update(title="Updated with .update()")

✔️ Useful when you don’t need to call save() or use model methods.


🧩 Optional: Update via Django Admin


✅ Best Practices

  • Use get_object_or_404() to avoid DoesNotExist errors
  • Validate data before saving (especially from forms)
  • Use update() for performance when changing many records
  • Prefer POST methods for updates in production

📌 Summary – Recap & Next Steps

🔍 Key Takeaways:

  • Use save() for individual object updates
  • Use update() for bulk QuerySet updates
  • Views, shell, and admin all support model updates
  • Always handle missing or invalid objects gracefully

⚙️ Real-World Relevance:
From blog posts to user profiles and product listings—data changes frequently, and safe updates are essential for reliability.


❓ Frequently Asked Questions (FAQ)

❓ What’s the difference between save() and update()?

save() updates a single object, calling model methods
update() changes fields directly in the database without model logic


❓ How do I update only some fields?

✅ Just assign values to the fields you want:

post.title = "New Title"
post.save(update_fields=['title'])

❓ How can I prevent updates to certain fields?

✅ Use editable=False in your model or exclude fields in forms.


❓ What if the record doesn’t exist?

✅ Use get_object_or_404() or handle DoesNotExist exceptions.


❓ Should I update data in a GET request?

🚫 No. Use POST or PUT for updates—GET should never change data.


Share Now :
Share

Django Update Data

Or Copy Link

CONTENTS
Scroll to Top