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
Links | Site |
---|---|
How to delete a record in Django models? | stackoverflow |
What does on_delete do on Django models? | stackoverflow |
How can i delete database table in django? | stackoverflow |