Is it possible to delete many Model instances without iterating over them and calling .delete() on each one?
Let's say we have something like this:
objects = [o for o in MyObject.objects.filter(...)]
objects_to_delete = get_validate_objects(objects) # some of objects from objects
And now I want to delete every MyObject in objects_to_delete.
Is there any better/smarter way than this?:
for o in objects_to_delete:
o.delete()
Also I want to be sure that all objects were deleted. Exception/message about problem during deleting object (deleted earlier) will be nice.
You can delete a queryset; to get a queryset containing the objects you have in a list you could do:
objects_to_delete = MyObject.objects.filter(pk__in=[o.pk for o in objects])
objects_to_delete.delete()
But ideally you would write "get_validate_objects" in such a way that it took a queryset as parameter and did all its checks on the queryset (using filter() and exclude() and the like). Then you could call .delete() on the result immediately. But that isn't always easy, of course.
Since you have objects in objects_to_delete, you can get the ids of those objects and delete. Do something like:
MyObject.objects.filter(id__in=[i.id for i in objects_to_delete]).delete()
It will result in the following SQL.
DELETE FROM MyObject WHERE id IN (ids of objects)
For e.g. if the id's of the objects to be deleted are 1,2, 3, 4, 5 then the sql will be:
DELETE FROM MyObject WHERE id IN (1, 2, 3, 4, 5)
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