Getting random records

Occasionally you may want to pull a random record from the database. You can accomplish this by ordering by the random or rand function (depending on your database):

Postgresql and Sqlite use the Random function:

  1. # Pick 5 lucky winners:
  2. LotteryNumber.select().order_by(fn.Random()).limit(5)

MySQL uses Rand:

  1. # Pick 5 lucky winners:
  2. LotterNumber.select().order_by(fn.Rand()).limit(5)