python – How to delete a record in Django models?

The Question :

318 people think this question is useful

I want to delete a particular record. Such as

delete from table_name where id = 1;

How can I do this in a django model?

The Question Comments :
  • Thanks for asking the question. Sometimes RTFM takes a lot longer than a Google search and SO, as evidenced by the number of answer up votes and the number of views
  • Agreed with @Freedom_Ben, but for future readers that like the f* manual anyway, this is what you’re looking for: docs.djangoproject.com/en/dev/topics/db/queries/…

The Answer 1

582 people think this answer is useful

There are a couple of ways:

To delete it directly:

SomeModel.objects.filter(id=id).delete()

To delete it from an instance:

instance = SomeModel.objects.get(id=id)
instance.delete()

The Answer 2

56 people think this answer is useful
MyModel.objects.get(pk=1).delete()

this will raise exception if the object with specified primary key doesn’t exist because at first it tries to retrieve the specified object.

MyModel.objects.filter(pk=1).delete()

this wont raise exception if the object with specified primary key doesn’t exist and it directly produces the query

DELETE FROM my_models where id=1

The Answer 3

20 people think this answer is useful

if you want to delete one instance then write the code

entry= Account.objects.get(id= 5)
entry.delete()

if you want to delete all instance then write the code

entries= Account.objects.all()
entries.delete()

The Answer 4

12 people think this answer is useful

If you want to delete one item

wishlist = Wishlist.objects.get(id = 20)
wishlist.delete()

If you want to delete all items in Wishlist for example

Wishlist.objects.all().delete()

The Answer 5

0 people think this answer is useful

you can delete the objects directly from the admin panel or else there is also an option to delete specific or selected id from an interactive shell by typing in python3 manage.py shell (python3 in Linux). If you want the user to delete the objects through the browser (with provided visual interface) e.g. of an employee whose ID is 6 from the database, we can achieve this with the following code, emp = employee.objects.get(id=6).delete()

THIS WILL DELETE THE EMPLOYEE WITH THE ID is 6.

If you wish to delete the all of the employees exist in the DB instead of get(), specify all() as follows: employee.objects.all().delete()

Add a Comment