How to get something random in datastore (AppEngine)?

后端 未结 4 2046
北荒
北荒 2020-12-01 18:28

Currently i\'m using something like this:

    images = Image.all()
    count = images.count()
    random_numb = random.randrange(1, count)
    image = Image.         


        
4条回答
  •  攒了一身酷
    2020-12-01 19:09

    Another solution (if you don't want to add an additional property). Keep a set of keys in memory.

    import random
    
    # Get all the keys, not the Entities
    q = ItemUser.all(keys_only=True).filter('is_active =', True)
    item_keys = q.fetch(2000) 
    
    # Get a random set of those keys, in this case 20 
    random_keys = random.sample(item_keys, 20)
    
    # Get those 20 Entities
    items = db.get(random_keys)
    

    The above code illustrates the basic method for getting only keys and then creating a random set with which to do a batch get. You could keep that set of keys in memory, add to it as you create new ItemUser Entities, and then have a method that returns a n random Entities. You'll have to implement some overhead to manage the memcached keys. I like this solution better if you're performing the query for random elements often (I assume using a batch get for n Entities is more efficient than a query for n Entities).

提交回复
热议问题