How to get something random in datastore (AppEngine)?

后端 未结 4 2055
北荒
北荒 2020-12-01 18:28

Currently i\'m using something like this:

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


        
4条回答
  •  被撕碎了的回忆
    2020-12-01 18:54

    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').get()
    

    Edit: Updated fall-through case per Nick's suggestion.

提交回复
热议问题