如何在数据存储区(AppEngine)中随机获取一些东西?
目前我正在使用这样的东西:
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)
但事实证明,AppEngine 上数据存储区中的 id 不是从 1 开始的.我在数据存储中有两个图像,它们的 ID 是 6001 和 7001.
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?
数据存储是分布式的,因此 ID 是非顺序的:两个数据存储节点需要能够同时生成一个 ID,而不会引起冲突.
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.
要获得随机实体,您可以在创建时为每个实体附加一个 0 到 1 之间的随机浮点数.然后查询,做这样的事情:
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()
根据尼克的建议更新了失败案例.
Updated fall-through case per Nick's suggestion.