Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django get a random object

Tags:

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] ?

like image 390
Erwan Avatar asked Apr 02 '14 15:04

Erwan


People also ask

How do I get random rows in Django?

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.

How does Django generate random numbers?

randint() method is used to generate a random number between the start and stop.


1 Answers

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.

like image 85
lukeaus Avatar answered Oct 09 '22 12:10

lukeaus