Updating Records by ID

Welcome to the section on updating records by ID using Django ORM. In our previous lessons, we learned how to retrieve records from a database. Now, we'll advance our skills and focus on updating specific records. This is crucial for any application that requires data modification, such as editing user profiles, updating products, or managing tasks.

What You'll Learn

In this lesson, you'll discover how to update a specific record in the database using its ID. This allows you to change the details of an item, which is a common requirement in many applications.

We will continue using the Todo model from our earlier lessons:

from django.db import models

class Todo(models.Model):
    task = models.CharField(max_length=200)
    completed = models.BooleanField(default=False)

    def __str__(self):
        return self.task

To update a Todo item by its ID, we'll add a new view function in views.py. This function will handle PUT requests to update the task field of the Todo object. Here’s the code snippet:

from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from django.shortcuts import get_object_or_404
from .models import Todo
import json

@csrf_exempt
@require_http_methods(['PUT'])
def update_todo(request, id):
    try:
        todo = get_object_or_404(Todo, id=id)
        data = json.loads(request.body)
        todo.task = data['task']
        todo.save()
        return JsonResponse({'message': 'Todo updated'})
    except Exception as e:
        return JsonResponse({'error': str(e)}, status=400)

This function first ensures that only PUT requests are accepted. It then retrieves the Todo object by its ID, updates its task field with new data from the request body, and saves the changes. If everything goes well, a JSON response with a success message is returned.

Why It Matters

Knowing how to update records is a fundamental skill in web development. Here are some scenarios where this knowledge is indispensable:

  • Editing User Profiles: Websites often allow users to update their profile information such as name, email, or address.
  • Managing Products: In e-commerce platforms, administrators need to update product details like price, description, and availability.
  • Task Management: To-do list applications often require functionality to update the details of tasks.

By mastering record updates, you will make your applications more interactive and user-friendly. Users expect to be able to modify data effortlessly, and your skills will ensure they can do so seamlessly.

Excited to dive in? Let's proceed to the practice section and start applying what we've learned. This hands-on experience will cement your understanding and boost your confidence in updating records by ID. Happy coding!

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal