Django Update Data
Modifying existing records in your database
✏️ What is Updating Data?
Updating data means modifying existing records in your database. Django provides multiple methods to update single or multiple records efficiently using model instances or querysets.
# Update a product price
product = Product.objects.get(id=1)
product.price = 899.99
product.save()
Key Update Methods
Get & Save
Retrieve, modify, then save
obj.field = value
obj.save()
Update Method
Update multiple records at once
Model.objects.update()
Filter & Update
Update specific records
Model.objects.filter().update()
Update or Create
Update if exists, create if not
update_or_create()
🔹 Method 1: Get, Modify, and Save
Retrieve a single record, change its fields, and save it back to the database. This is the most straightforward method for updating individual records.
# models.py
from django.db import models
class Product(models.Model):
name = models.CharField(max_length=100)
price = models.DecimalField(max_digits=10, decimal_places=2)
stock = models.IntegerField()
# Get the product
product = Product.objects.get(id=1)
# Update fields
product.price = 899.99
product.stock = 45
# Save changes
product.save()
print(f"Updated {product.name}: ${product.price}, Stock: {product.stock}")
Output:
Updated Laptop: $899.99, Stock: 45
🔹 Method 2: Using update() Method
Update multiple records at once using the update() method on a queryset:
# Update all products with stock less than 10
updated_count = Product.objects.filter(stock__lt=10).update(
stock=100
)
print(f"Updated {updated_count} products")
Output:
Updated 5 products
⚠️ Important Note:
The update() method is faster but doesn't call save() method or send signals. Use it for bulk updates.
🔹 Update Specific Records
Use filters to update only records that match certain conditions:
# Update products by category
Product.objects.filter(category='electronics').update(
discount=10
)
# Update products with price greater than 500
Product.objects.filter(price__gt=500).update(
shipping_free=True
)
# Update single product by name
Product.objects.filter(name='Laptop').update(
price=799.99,
stock=30
)
print("Products updated successfully")
Output:
Products updated successfully
🔹 Update with F() Expressions
Use F() to reference field values in updates:
from django.db.models import F
# Increase all prices by 10%
Product.objects.all().update(
price=F('price') * 1.10
)
# Decrease stock by 1 for all products
Product.objects.all().update(
stock=F('stock') - 1
)
# Double the discount
Product.objects.filter(discount__gt=0).update(
discount=F('discount') * 2
)
print("Prices and stock updated")
Output:
Prices and stock updated
🔹 Update or Create
Update a record if it exists, or create it if it doesn't:
# Update or create product
product, created = Product.objects.update_or_create(
name='Laptop',
defaults={
'price': 999.99,
'stock': 50,
'category': 'electronics'
}
)
if created:
print(f"Created new product: {product.name}")
else:
print(f"Updated existing product: {product.name}")
Output (if updated):
Updated existing product: Laptop
🔹 Update from Forms
Update records from user input in views:
# views.py
from django.shortcuts import render, redirect, get_object_or_404
from .models import Product
def edit_product(request, product_id):
product = get_object_or_404(Product, id=product_id)
if request.method == 'POST':
# Get updated data from form
product.name = request.POST.get('name')
product.price = request.POST.get('price')
product.stock = request.POST.get('stock')
# Save changes
product.save()
return redirect('product_list')
return render(request, 'edit_product.html', {'product': product})
<!-- templates/edit_product.html -->
<form method="post">
{% csrf_token %}
<input type="text" name="name" value="{{ product.name }}">
<input type="number" name="price" step="0.01" value="{{ product.price }}">
<input type="number" name="stock" value="{{ product.stock }}">
<button type="submit">Update Product</button>
</form>
🔹 Partial Updates
Update only specific fields without affecting others:
# Update only the price field
product = Product.objects.get(id=1)
product.price = 699.99
product.save(update_fields=['price'])
# Update multiple specific fields
product.price = 799.99
product.stock = 25
product.save(update_fields=['price', 'stock'])
print(f"Updated price and stock for {product.name}")
Output:
Updated price and stock for Laptop