So i got the database.objects.all() and database.objects.get('name') but how would i got about getting one random item from the database. I'm having trouble trying to figure out how to get it ot select one random item.
3 Answers
Selecting a random element from a list of all database objects isn't a goog solution as retrieving all elements of the database can have a big impact on performance, neither is using order_by('?') as mentioned in the django documentation.
The best solution should be to retrieve an element with a random index:
import random
random_idx = random.randint(0, Model.objects.count() - 1)
random_obj = Model.objects.all()[random_idx]
5 Comments
values_list and you would have let's say millions of records, django will need to fetch the id of every object.Aamir's solution will select all objects before discarding all but one. This is extremely wasteful and, besides, this sort of calculation should be done in the database.
model.objects.all().order_by('?')[0]
Read more here: https://docs.djangoproject.com/en/dev/ref/models/querysets/#order-by
Edit: lazerscience's answer is indeed faster, as shown here.
1 Comment
Note: order_by('?') queries may be expensive and slow...I would do it slightly different. Querysets are lazy anyway in django.
import random
def get_my_random_object():
object = random.choice(model.objects.all())
return object
https://docs.djangoproject.com/en/dev/topics/db/queries/#querysets-are-lazy https://docs.djangoproject.com/en/dev/ref/models/querysets/#when-querysets-are-evaluated