Mastering Django ORM Update Queries — From Basics to Pro Level
Updating data properly is just as important as selecting data.
In this guide, you will learn how to update records correctly in Django ORM — from basic .save()
usage to pro techniques like atomic updates, bulk updates, F expressions, and best practices!
📚 1. Basic Update Using .save()
Fetch and modify a single object
user = NewUser.objects.get(pk=1)
user.email = 'newemail@example.com'
user.save()
⚡ 2. Updating Specific Fields with .save(update_fields=[...])
user = NewUser.objects.get(pk=1)
user.email = 'newemail@example.com'
user.save(update_fields=['email'])
🎯 3. Updating Multiple Records at Once Using .update()
NewUser.objects.filter(user_type=2).update(is_active=False)
🧠 4. .save() vs .update() — Key Differences
Aspect | .save() | .update() |
---|---|---|
Works on | Single object | QuerySet (multiple) |
Triggers signals? | ✅ Yes | ❌ No |
Auto-updates auto_now fields? | ✅ Yes | ❌ No |
Custom logic inside save() runs? | ✅ Yes | ❌ No |
Speed for bulk | ❌ Slow | ✅ Fast |
🔥 5. Updating with F Expressions (Atomic Updates)
from django.db.models import F
NewUser.objects.filter(pk=1).update(credit_point=F('credit_point') + 10)
🛠 6. Update with Conditions (Smart Filtering)
NewUser.objects.filter(user_type=2, is_active=True).update(is_verified=True)
📋 7. Important Tips When Updating
- Always use
.save(update_fields=[...])
if you know what changed. - Use
.update()
if you want to bulk update many records. - Use
F()
expressions when updating values based on themselves (like counters). - Be careful:
.update()
skips signals and custom model logic.
🧠 8. Handling auto_now and Timestamps
from django.utils import timezone
NewUser.objects.filter(pk=1).update(modified_at=timezone.now())
🚀 9. Handling Race Conditions (Advanced)
from django.db import transaction
with transaction.atomic():
user = NewUser.objects.select_for_update().get(pk=1)
user.credit_point += 10
user.save()
🎯 10. Best Practices for Updates
- ✅ Always filter properly before updating.
- ✅ Use
.save(update_fields=...)
if updating only some fields. - ✅ Use
.update()
when updating many records at once. - ✅ Be cautious:
.update()
skips signals and model logic. - ✅ Use
F()
expressions for safe, concurrent field changes. - ✅ Handle timestamps manually during
.update()
.
📖 Final Example — Updating Cleanly
# Safe update of user email
user = NewUser.objects.get(pk=5)
user.email = 'updated_email@example.com'
user.save(update_fields=['email'])
# Bulk deactivate all sellers
NewUser.objects.filter(user_type=2).update(is_active=False)
# Increment credit points safely
NewUser.objects.filter(pk=5).update(credit_point=F('credit_point') + 50)
Comments
Post a Comment