订购查询

Ordering a query

下面的这组查询将一组配置文件连接在一起以返回到网站。

我想用这些进行查询,因为我想对整个配置文件集合使用排序功能。

# Get all users for who 'currentUser' is an assistant for.
users = Users.query(Users.assistant.IN(currentUser)).fetch()

# Get all profiles that belong to those users and have not been deleted.
for user in users:
    profiles = profiles + Profiles.query(
            ndb.AND(
            Profiles.user == user.username,
            Profiles.deleted == False
        )
    ).order(Profiles.history).fetch() # Order all profiles by timestamp

您要查找的内容在某种程度上等同于:

# get the list of usernames obtained above
usernames = [user.username for user in users]

profiles = Profiles.query(ndb.AND(Profiles.user.IN(usernames),
                                  Profiles.deleted == False))
                         .order(Profiles.history).fetch()

但是如果 usernames 包含许多元素(显然超过 10 个左右),这将有性能问题,请参见 Does the NDB membership query ("IN" operation) performance degrade with lots of possible values?