开发者

How to get a set of unique random entries from the Datastore

开发者 https://www.devze.com 2023-03-05 23:47 出处:网络
I used a slightly modified solution from this thread to get a set of randomly chosen items 开发者_如何学编程from Datastore. I use ProtoRPC, though it doesn\'t make much difference, just for your infor

I used a slightly modified solution from this thread to get a set of randomly chosen items 开发者_如何学编程from Datastore. I use ProtoRPC, though it doesn't make much difference, just for your information. My code looks like this:

@remote.method(RandomImagesRequest, RandomImagesResponse)
def get_random_images(self, request):
    images = []
    count = request.count
    for i in range(0, count):
        random_number = random.random()
        img = Image.all().order('random_number').filter('random_number>=', random_number).get()
        if img is None:
            img = Image.all().order('-random_number').filter('random_number <', random_number).get()
        image_message = ImageMessage(image_url=img.image_url)
        images.append(image_message)
    return RandomImagesResponse(images=images)

This way I get any number of randomly chosen items. But sometimes there duplicates appear. How to effectively get only unique items from Datastore?


Instead of fetching N items separately, just do a fetch for three items where random_number >= the new random_number.

The downside is that you will occasionally get 0-2 items, in which case if you absolutely need 3 items you can re-fetch the rest with another random number (or switch the >= to a <)


You could just check to make sure the entity's key is not in your images list before appending it, and requery if it is. Just make sure you have at least count items in the database or else it will loop infinitely.

0

精彩评论

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

关注公众号