如何在数据存储区(AppEngine)中随机获取一些东西? [英] How to get something random in datastore (AppEngine)?

查看:21
本文介绍了如何在数据存储区(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.

这篇关于如何在数据存储区(AppEngine)中随机获取一些东西?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆