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
?
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
?
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()
pre_delete
or post_delete
signal instead.
– Wolph
Sep 28 '10 at 8:00
delete()
to check what you were deleting. It returns a tuple with the count of deleted objects and a dictionary with details about the deleted types, e.g. (1, {'yourapp.SomeModel': 1})
.
– mcb
Jul 31 '17 at 14:31
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
Wolph provided a good answer focused codes. Let me just paste official doc here, for people's reference.
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()