473

I want to delete a particular record like:

delete from table_name where id = 1;

How can I do this in a django model?

Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
user426795
  • 11,073
  • 11
  • 35
  • 35
  • 13
    Agreed with @Freedom_Ben, but for future readers that like the f* manual anyway, this is what you're looking for: https://docs.djangoproject.com/en/dev/topics/db/queries/#topics-db-queries-delete – Dinei Feb 24 '17 at 12:07

10 Answers10

810

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()
Wolph
  • 78,177
  • 11
  • 137
  • 148
  • 98
    Note that the first one will not call the .delete() method of the object, so if you have 'cleanup' code in that method it will not be called. Generally not an issue, but worth keeping in mind. – Matthew Schinckel Sep 28 '10 at 00:08
  • 13
    @Matthew Schinckel: that is true. If you want to have a custom delete method than you should be using the `pre_delete` or `post_delete` signal instead. – Wolph Sep 28 '10 at 08:00
  • 2
    I dont know what is the case after DJango 1.4, but this is actually fetching all the PKs and then delete by those PKs. So eg if you delete by an arbitrary field, this can be way slower then the SQL counterpart... :( – Vajk Hermecz Mar 25 '14 at 16:22
  • 1
    @VajkHermecz: that is true and the expected behaviour because of the delete signals. The Django signals system has to track all database changes because something could hook to it (like reversion does). – Wolph Mar 25 '14 at 20:35
  • 1
    Could you use this? `SomeModel.objects.get(id=id).delete()` – Foxocube Jul 16 '15 at 16:17
  • 1
    @CyberJacob: yes, delete works on both models and querysets – Wolph Jul 16 '15 at 19:13
  • 1
    Note that delete does not work on the base model object (it's the only model method that doesn't) as a deliberate move to reduce accidental deletion. If you want to delete everything you'll need to use the "all()" filter like this: SomeModel.objects.all().delete() – Ezekiel Kruglick Jan 20 '16 at 01:33
  • 1
    worth noting: the first option which uses the filter returns a queryset. this means that if you do not filter by primary key you will delete multiple records. i realize the question was asking particularly about the id but still worth putting this out there as a friendly reminder. – Gil Hiram Jul 22 '16 at 14:43
  • 9
    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.SomeModel': 1})`. – mcb Jul 31 '17 at 14:31
  • 1
    Just for my understanding : do we need to call the save() method after deleting? – Aravind Pillai Aug 21 '18 at 08:55
  • 1
    Saving is for inserting and updating records so you don't want that while deleting. – Wolph Aug 21 '18 at 12:03
  • 1
    how to delete 2+ entries? like `id in 1,2,3,4,5,6` – Toskan Jun 10 '19 at 01:46
  • 1
    @Toskan pretty much exactly like that: `SomeModel.objects.filter(id__in=[ 1,2,3,4,5,6]).delete()` – Wolph Jun 10 '19 at 02:03
85
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
Milad Khodabandehloo
  • 1,907
  • 1
  • 14
  • 24
  • You have used `pk`, @Wolph used `id`. What is the difference? – Gathide May 22 '21 at 04:05
  • With `pk` you are filtering using the table primary key. I think @Milad assumed that since @Wolf was using `id` he was searching on the primary key. Generally this could be wrong if you set a different field as primary key in your model – Simone Pozzoli May 27 '21 at 08:50
  • 1
    @Gathide You can see in django https://docs.djangoproject.com/en/3.2/topics/db/models/that ```id = models.BigAutoField(primary_key=True)``` Therefore, if you have not changed the defualt primary key of your model, both ***id*** or ***pk*** work because ***pk** refers to primary key. – Milad Khodabandehloo May 29 '21 at 13:21
28

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()
ColeDrain
  • 3
  • 2
18

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()
Ahmed Adewale
  • 2,943
  • 23
  • 19
10

Extending the top voted answer by wolph

Note that you should pass request as a parameter to your delete function in your views. An example would be like:

from django.shortcuts import redirect


def delete(request, id):
YourModelName.objects.filter(id=id).delete()

return redirect('url_name')
KhairulBashar
  • 141
  • 1
  • 9
  • Which is 'the top voted comment'? It is better is you reference it, e.g. by its author, as it may not remain 'top' forever. – Gathide May 22 '21 at 03:40
8

The delete() method is used to delete model instances from a database.This method immediately deletes the object. this method returns the number of object deleted.

Example:

For deleting one record:

data_to_be_deleted = Modelname.objects.get(fieldname = value)
data_to_be_deleted.delete()

As get method returns a single object from queryset only single record will be deleted.If value supplied doesn't exist this will throw an error.If there are multilpe records in table for same value then also it will throw an error so good practice is to use a single unique value while using get.

For deleting multiple record according to a condition:

For condition based deletion filter method is used on queryset and then delete is called.

data_to_be_deleted = Modelname.objects.filter(fieldname = value)
data_to_be_deleted.delete()

For deleting all records:

For deletion of all model instances/records from database table you need to call delete method on all

data_to_be_deleted = Modelname.objects.all()
data_to_be_deleted.delete()

Note: code can be written in single line as Modelname.objects.all().delete(), but for clear understanding, I have used multiple lines.

Zoe
  • 27,060
  • 21
  • 118
  • 148
Ashish Nautiyal
  • 861
  • 6
  • 8
4

You can also use get_object_or_404(), rather than directly using get() as while using get() we explicitly raise the error of 404.

But, while using get_object_or_404 it is automatically done.

get_object_or_404 According to 4.0 docs, Calls get() on a given model manager, but it raises Http404 instead of the model’s DoesNotExist exception.

Use it like:

For bulk deletion:

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

For deleting single instance, use get_object_or_404() instead of get() in the following way:

instance=get_object_or_404(anyModel,id=id)
instance.delete()

If, not found raises 404 automatically.

Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
2

It is as simple as calling the following.

SomeModel.objects.get(pk=1).delete()
# Or
SomeModel.objects.filter(pk=1).delete()

# SQL equivalent
# delete from table_name where id = 1;

In case you want to remove multiple records based on id, use the __in query lookup

SomeModel.objects.fitler(pk__in=[1,2,3,4,5,...]).delete()

# SQL equivalent
# delete from table_name where id in (1,2,4,5,...);

In case you want to delete all records, use .all() to retrieve all queries, then .delete().

SomeModel.objects.all().delete()

# SQL equivalent
# delete from table_name;
Radwan Abu-Odeh
  • 1,897
  • 9
  • 16
1

The way I do it:

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

instance.delete()

For me it looks easy to understand, that's why I use this approach.

Zoe
  • 27,060
  • 21
  • 118
  • 148
lionel
  • 140
  • 1
  • 2
  • 12
0

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