Django get a random object

Just been looking at this. The line:

random_object = A.objects.order_by('?')[0]

has reportedly brought down many servers.

Unfortunately Erwans code caused an error on accessing non-sequential ids.

There is another short way to do this:

import random

items = list(Product.objects.all())

# change 3 to how many random items you want
random_items = random.sample(items, 3)
# if you want only a single random item
random_item = random.choice(items)

The good thing about this is that it handles non-sequential ids without error.

Leave a Comment