How to delete a record in Django models? How to delete a record in Django models? django django

How to delete a record in Django models?


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()


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


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()