Django Models – Update Data

Last updated 3 weeks, 2 days ago | 82 views 75     5

Tags:- Python Django

In Django, updating data in the database is easy and intuitive, thanks to its powerful Object-Relational Mapper (ORM). Once you’ve defined your models and inserted data, you can update it:

  • From the Python shell

  • Through views (e.g., in response to form submissions)

  • Using Django Admin

  • Using QuerySet update operations

This article explains all the ways to update data in Django models, complete with examples and best practices.


Common Update Methods

Method Description
.save() Update a specific instance
.update() Bulk update multiple records
Django Admin Manual update via web UI
View logic Update via form submissions or APIs

✅ Example Model

We’ll use this Post model for all examples:

# blog/models.py

from django.db import models

class Category(models.Model):
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name

class Post(models.Model):
    title = models.CharField(max_length=200)
    content = models.TextField()
    published = models.BooleanField(default=False)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.title

Method 1: Update a Single Object Using .save()

from blog.models import Post

# Get the object
post = Post.objects.get(id=1)

# Update the fields
post.title = "Updated Title"
post.published = True

# Save the changes
post.save()

✅ Best for updating one record with custom logic.


Method 2: Bulk Update Using .update()

from blog.models import Post

# Update all unpublished posts to published
Post.objects.filter(published=False).update(published=True)

✅ Efficient for updating multiple records at once.
⚠️ Skips save() and model signals.


Method 3: Update in Django Admin

  1. Ensure your model is registered in admin.py:

from django.contrib import admin
from .models import Post

admin.site.register(Post)
  1. Go to /admin/, log in, and edit posts using the web interface.

✅ Great for manual updates during development or small-scale admin tasks.


Method 4: Update via View Logic (e.g., Form Submission)

Here’s an example of updating a post using data from a form.

# blog/views.py

from django.shortcuts import get_object_or_404, redirect, render
from .models import Post

def update_post(request, post_id):
    post = get_object_or_404(Post, id=post_id)

    if request.method == "POST":
        post.title = request.POST.get('title')
        post.content = request.POST.get('content')
        post.published = 'published' in request.POST
        post.save()
        return redirect('post_detail', post_id=post.id)

    return render(request, 'update_post.html', {'post': post})

✅ Allows you to update data based on user input.


Method 5: Using get_or_create() + Update

Useful when you want to create or update based on existence:

category, created = Category.objects.get_or_create(name="Django")

if not created:
    category.name = "Updated Django"
    category.save()

Full Example Script

# Run in Django shell
from blog.models import Post, Category

# Update an existing post
post = Post.objects.get(title="Old Title")
post.title = "New Title"
post.published = True
post.save()

# Bulk update all draft posts
Post.objects.filter(published=False).update(published=True)

✅ Tips for Updating Data in Django

Tip Why It’s Helpful
Use .save() for single records Triggers signals, handles auto_now, and is safer
Use .update() for bulk updates Much faster for many records
Use get_or_create() Clean way to insert or update
Avoid saving in loops Use bulk operations if performance matters
Keep business logic separate Avoid putting complex logic in views or directly in model updates

⚠️ Common Pitfalls

Pitfall Solution
Forgetting to call .save() Changes to object fields won’t persist without .save()
Using .update() on a single object Doesn’t update timestamps or trigger signals
Updating auto_now fields manually Django will override them unless changed programmatically
Not checking if object exists Use get_object_or_404() or exception handling
Ignoring validation Use Django forms or serializers when taking user input

Conclusion

Django’s ORM makes updating database records clean, safe, and powerful. Whether you're editing a single post or updating hundreds of records at once, Django provides the tools to do it efficiently and with minimal code.

Mastering model updates will help you build dynamic, responsive web applications that manage data with confidence.