Django delete data

Prerequisites

Django shell

  • Run the command python manage.py shell open the django shell.

Django Model - Contact

my_app/models.py

from django.db import models

class Contact(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    email = models.EmailField(max_length=255)
    phone = models.CharField(max_length=10, null=True)

    class Meta:
        db_table = "contact"

Add few records to database

from my_app.models import Contact

contacts = [
    {"first_name": "Anji", "last_name": "K", "email": "anji@example.com"},
    {"first_name": "Jessi", "last_name": "M", "email": "jsessi@example.com"},
    {"first_name": "Jessi", "last_name": "L", "email": "jsessil@example.com"},
]
objects = [Contact(**d) for d in contacts]
results = Contact.objects.bulk_create(objects)

delete a single record - delete()

  • use delete() method on the model object to delete it.
from my_app.models import Contact

obj = Contact.objects.get(first_name="Anji")
obj.delete()
  • Check the database if the record deleted or not.

delete multiple records - delete()

  • use delete() method on the django queryset.
from my_app.models import Contact

queryset = Contact.objects.filter(first_name="Jessi")
queryset.delete()
  • Check the database if the record deleted or not.

References