Deleting a record

To delete a record in the database, we must use the delete() method. Removing items is easier than changing items, because the method is the same for a queryset as for the instances of models. An example of this is as follows:

from TasksManager.models import Task
from django.shortcuts import render
def page(request):
  one_task = Task.objects.get(id = 1)
  one_task.delete() # line 1
  all_tasks = Task.objects.all()
  all_tasks.delete() # line 2
  return render(request, 'en/public/index.html', {'action' : 'Delete tasks'})

In this example, line 1 removes the stain with id = 1. Then, line 2 removes all the present tasks in the database.

Be careful because even if we use a web framework, we keep hold of the data. No confirmation will be required ...

Get Django: Web Development with Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.