开发者

Fetch a random entity from the datastore

Pretty simple,开发者_C百科 in my AppEngine application, I have over 1 million entities of one kind, what is the best way to pick one at random?


Maybe one solution but i don't know if it's the best :)

import random
from google.appengine.ext import db
from google.appengine.api import memcache

DATA_KEY = "models/keys/random"

def get_data():
    data = memcache.get (DATA_KEY)
    if data is None:
        offset = random.randint (1, 1000000)
        data  = self.MyModel.all (keys_only=True).fetch (100, offset)
        memcache.add (DATA_KEY, data, 60)

    entity_key = random.choice (data)
    return db.get (entity_key)


See this question:

Fetching a random record from the Google App Engine Datastore?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜