How to delete a row in a table with Django ?

Created September 11, 2022 | Viewed 441 | by Benjamin Edit


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

q.delete()

Note: before deleting a row, it is important to know how on_delete has been defined in the database. Check the models.py 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:

User.objects.all().delete()

Delete rows with a condition

Use a filter:

User.objects.filter(username='JohnDoe').delete()

References