[Answered ]-Removing objects from a queryset by ID optimal implementation

1👍

The current approach will query the database 1000000 times, you can use __in
lookup and do bulk deletion by applying delete() just after filter():

MyModel.objects.filter(pk__in=ids).delete()

Now the database would be affected only one time.

Edit:

To filter all the valid IDs in optimal way do intersection in the following way:

all_existing_ids = set(MyModel.objects.values_list('pk', flat=True))
all_valid_ids = set(ids) & existing_ids

Leave a comment