I am trying to get a random object from a model A
For now, it is working well with this code:
random_idx = random.randint(0, A.objects.count() - 1) random_object = A.objects.all()[random_idx]
But I feel this code is better:
random_object = A.objects.order_by('?')[0]
Which one is the best? Possible problem with deleted objects using the first code? Because, for example, I can have 10 objects but the object with the number 10 as id, is not existing anymore? Did I have misunderstood something in A.objects.all()[random_idx] ?
ORDER BY RAND() LIMIT N query. It means that for every row in table the RAND() function will be executed, then the whole table will be sorted according to value of this function and then first N records will be returned.
randint() method is used to generate a random number between the start and stop.
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.
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