Trying to get a random object from the database with an id. Some ids in the database table are missing, for example, 1, 2, 4, 5, 6, 19, 20... so I need to make sure I don't get an error when I try to get an object.
This seems to be working. Is there a better way.
def get_random_title():
title_count = OriginalTitle.objects.count()
random_id = random.randrange(1, title_count)
random_title_obj = None
while random_title_obj is None:
try:
random_title_obj = OriginalTitle.objects.get(id=random_id)
except ObjectDoesNotExist:
continue
return random_title_obj.title
def play(request):
random_title = get_random_title()
context = {
'original_title': random_title
}
return render(request, 'game/game.html', context)
CodePudding user response:
You can use random.sample() on a QuerySet object. or change the ordering of rows.
OriginalTitle.objects.order_by('?')[:1]
CodePudding user response:
# edit your get_random_title
def get_random_title():
random_title_obj = OriginalTitle.objects.order_by('?')[0]
return random_title_obj.title
please read more details in this answer