Select random mysql with Django

Asked

Viewed 32 times

-1

I have this code that selects randomly, users on my DB:

def select_random(request):
    try:
      last = User.objects.count() - 1

      index_one = random.randint(0, last)
      index_two = random.randint(0, last - 1)

      if index_two == index_one:
        index_two = last

      object_user = User.objects.all()[index_one]

      return object_user
    except:
      return False

The problem: If there are enough users to select, this can give problem right?

Is there any way to do this by using Django?

Or is there another way to do it independently if you use the functions of Django? In the case, gambiarra?

  • The guys can not answer, negative the question and not comment. I joke this.

1 answer

0


If I understand correctly, you want to return a random user, then follows:

User.objects.all().order_by('?').first()

The . first() is equivalent to [0].

You can read more about ordering here.

  • Yes, that’s right, however, that’s not correct, at least I’ve researched it, and most places say that using it on a server with a lot of data can be bad!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.