Rage
Rage

Reputation: 970

Is it possible to retrieve 'id' field of objects deleted in Django .delete()?

When executing the following query, is there a mechanism in place to return a list of the 'id's of the objects that have been deleted?

>>> MyModel.objects.all().delete()
>>> (430, {'myapp': 430})

Upvotes: 3

Views: 1334

Answers (1)

ruddra
ruddra

Reputation: 52028

I don't think its possible unless you delete objects one by one. From documentation:

Keep in mind that this will, whenever possible, be executed purely in SQL, and so the delete() methods of individual object instances will not necessarily be called during the process

Means MyModel.objects.all().delete()(or bulk delete operation) will be executed in SQL level, so each object will not be called.

If you want to delete objects one by one, then you can try like this:

deleted = []
for item in MyModel.objects.all():
   deleted.append(item.id)
   item.delete()
print(deleted)

But it will very inefficient solution and not recommended.

Upvotes: 5

Related Questions