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

查看:83
本文介绍了如何在数据存储区(AppEngine)中随机获取某些内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  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。



有没有更好的方法来检索随机图像? 解决方案

数据存储是分布式的,因此ID是非顺序的:两个数据存储节点需要能够同时生成一个ID而不会造成冲突。



要获得一个随机实体,您可以在创建时将0和1之间的随机float添加到每个实体。然后查询,做这样的事情:

  rand_num = random.random()
entity = MyModel.all ).order('rand_num')。filter('rand_num> =',rand_num).get()
如果实体是None:
entity = MyModel.all()。order('rand_num' ).get()

编辑:建议。


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?

解决方案

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.

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

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