开发者

Fetch a random entity from the datastore

开发者 https://www.devze.com 2023-01-15 15:03 出处:网络
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 :)

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

精彩评论

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