Delete records in Django models?

Last updated 1 month ago | 86 views 75     5

Tags:- Django

Django | Delete records in Django models

Delete query performs an SQL delete query on all rows in the queryset and returns the number of objects deleted and a dictionary with the number of deletions per object type.

Delete from an instance

customer = Customer.objects.all().get('customer_id'=5)
customer.delete()

OR

Customer.objects.get('customer_id'=5).delete()

The get() query raises an exception if the object does not exist because at first, it tries to retrieve the specified object and then performs a delete operation.


To delete it directly:

customer = Customer.objects.filter('customer_id'=5)
customer.delete()

OR

Customer.objects.filter('customer_id'=5).delete()

this does not raise any exception if the object does not exist and it directly produces the query

DELETE FROM Customer where customer_id=5

Delete all instance

Customer_all= Customer.objects.all()
Customer_all.delete()

OR

Customer.objects.all().delete()