How to delete a row in a table with Django ?

Published: September 11, 2022

Tags: Django; Protection Status

Example of how to delete a row in a table with Django

Deleting a row in a table

To delete for example a user, a solution is to use delete().

Select for example the user with id = 1:

 q = User.objects.get(pk=1)

then enter


Note: before deleting a row, it is important to know how on_delete has been defined in the database. Check the file What does on_delete do on Django models?. In most cases:

CASCADE: When the referenced object is deleted, also delete the objects that have references to it (when you remove a blog post for instance, you might want to delete comments as well). SQL equivalent: CASCADE.

So for example all rows associated with User id = 1:

models.ForeignKey(User, on_delete=models.CASCADE)

will also be deleted.

Delete all rows in a table

Delete all users:


Delete rows with a condition

Use a filter: