member_query = Member.query(Member.account==account)
member_query 现在包含一个 Query 实例。
从那里,您有几个选项,但您似乎只想从此查询中获取一个实体。要做到这一点,你会说。
member = Member.query(Member.account==account).get()
现在,如果帐户不存在,则 member 为 None,或者将包含 Member 模型实例。
如果使用 .fetch(),则可以指定要检索的实体数量作为第一个参数,或使用 None(或无参数)获取所有实体。如果有很多实体符合此条件,这可能会很耗时。
另一种范例是遍历查询并中断或返回与您的条件匹配的第一个实体。此范例将允许您执行查询参数未涵盖的即时条件。比如……
for member in member_query:
if member.active:
return member
# No account
return None
但是,对这种成员资格模型进行查询并不理想,因为它每次都需要运行一个查询。当然,如果您希望“用户”能够访问多个“个人资料”(例如 Facebook 用户 Facebook 页面),您需要这样的东西。
构建帐户有权访问的“个人资料”列表的效率要高得多,如下所示:
class UserAccount(ndb.Model):
"""User Account"""
"""List of keys which reference profiles this user can access"""
profiles = ndb.KeyProperty(repeated=True)
def fetch_profiles(self):
"""Returns a list of profile entities this user can access"""
return ndb.get_multi(profiles)
def can_user_access_profile(self, profile):
"""Returns True if user can access 'profile' (either a ndb.Model or ndb.Key)"""
if isinstance(profile, ndb.Model):
profile = profile.key() # Convert Model instances to a key
return profile in self.profiles
class Profile(ndb.Model):
# ...
如您所见,这还可以让您快速确定用户是否有权访问给定的个人资料。