How to get 10 random gae ndb objects?

I have the following class for storing my records:

class List(ndb.Model):
    '''
    Index
      Key:              sender
    '''
    sender = ndb.StringProperty()
    ...
    counter = ndb.IntegerProperty(default=0)
    ignore = ndb.BooleanProperty(default=False)

    added = ndb.DateTimeProperty(auto_now_add=True, indexed=False)
    updated = ndb.DateTimeProperty(auto_now=True, indexed=False)

The following code is used to return all the objects I need:

entries = List.query()
entries = entries.filter(List.counter > 5)
entries = entries.filter(List.ignore == False)
entries = entries.fetch()

How do I change the code to get 10 random entries from entries? I plan to have a daily cron task to retrieve random entries, so they should be really random. What is the best way to get these records (to minimize the number of read operations)?

I don't think the best code is:

entries = random.sample(entries, 10)
+4
source share
1 answer

, , , - , .

,

list_query = List.query()
list_query = list_query.filter(List.counter > 5)
list_query = list_query.filter(List.ignore == False)
list_keys = list_query.fetch(keys_only=True) # maybe put a limit here.

list_keys = random.sample(list_keys, 10)
lists = [list_key.get() for list_key in list_keys]
+3

Source: https://habr.com/ru/post/1525939/


All Articles