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?
To delete a record we do not need a new template, but we need to make some changes to the members template. Of course, you can chose how you want to add a delete button, but in this example, we will add a "delete" link for each record in a new table column. The "delete" link will also contain the ID of each record.
The Django signals system has to track all database changes because something could hook to it (like reversion does). You can use the return value of 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.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With