Gustavo Reyes Gustavo Reyes - 6 months ago 10
Python Question

Delete N random objects Django orm

How can I delete 100 randomly selected objects in Django?

Example:

Book.objects.all()[:100].delete()

Answer

I can't understand when this would be useful, but here's one way

import random
ids = random.sample(Book.objects.values_list('pk', flat=True), 100)
Book.objects.filter(pk__in=ids).delete()