Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete a record in Django models?

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?

like image 302
user426795 Avatar asked Sep 27 '10 16:09

user426795


People also ask

How do I delete a specific record in Django?

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.

How do I delete a query in Django?

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.


2 Answers

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() 
like image 177
Wolph Avatar answered Sep 30 '22 19:09

Wolph


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 
like image 40
Milad Khodabandehloo Avatar answered Sep 30 '22 20:09

Milad Khodabandehloo