Deleting multiple rows from your database

There are 2 ways of doing this.

1 - Efficient..BUT..

MyModel.objects.filter(expired=True).delete()

This method, at the time of writing, does not call the delete function created in your Django models. If you have not created your own delete function, go ahead and use the above code.

2 - Less efficient..BUT..

rows = MyModel.objects.filter(expired=True)

for r in rows:
    r.delete()

This method does call your own delete function. There is obviously a bit more overhead due to requesting the rows, and deleting each row manually. However, if you have your own delete function, you probably want to run it.

Comments

Posted by Val L33 on 19th Mar 2011 04:15

you may want to remove the .delete() from the filter line of your second method.

Posted by PiGGeH on 19th Mar 2011 11:53

Fixed. thanks for the note.