views:

62

answers:

2

Currently i'm using something like this:

    images = Image.all()
    count = images.count()
    random_numb = random.randrange(1, count)
    image = Image.get_by_id(random_numb)

But it turns out that the ids in the datastore on AppEngine don't start from 1. I have two images in datastore and their ids are 6001 and 7001.

Is there a better way to retrieve random images?

+4  A: 

The datastore is distributed, so IDs are non-sequential: two datastore nodes need to be able to generate an ID at the same time without causing a conflict.

To get a random entity, you can attach a random float between 0 and 1 to each entity on create. Then to query, do something like this:

rand_num = random.random()
entity = MyModel.all().order('rand_num').filter('rand_num >=', rand_num).get()
if entity is None:
  entity = MyModel.all().order('-rand_num').filter('rand_num <', rand_num).get()
Drew Sears
A: 

Another (less efficient) method, which requires no setup:

query = MyModel.all(keys_only=True)

# query.filter("...")

selected_key = None
n = 0
for key in query:
  if random.randint(0,n)==0:
    selected_key = key
  n += 1

# just in case the query is empty
if selected_key is None:
  entry = None
else:
  entry = MyModel.get(selected_key)
pix