NDB使用Users API形成实体组

Sol*_*oub 2 python google-app-engine data-modeling google-cloud-datastore

我试图围绕一个看起来很简单的用例,但我似乎失败了.此练习的目标是为使用高复制数据存储区中的Google帐户用户名登录的用户查找一组记录,并且非常一致.

我的数据如下:

class Account(ndb.Model):
    owner = ndb.UserProperty()
    name = ndb.StringProperty()

class Content(ndb.Model):
    content = ndb.StringProperty()
Run Code Online (Sandbox Code Playgroud)

当我第一次创建帐户时,我只是执行以下操作:

current_user = users.get_current_user()
new_account = Account(owner=current_user, name='Some Name')
new_account.put()
Run Code Online (Sandbox Code Playgroud)

现在创建内容:

new_content = Content(parent=new_account.key, content='Some Content')
new_content.put()
Run Code Online (Sandbox Code Playgroud)

当用户登录时,我只能通过UserProperty查询,但我似乎无法将用户设置为实体组的父级,因此如何确保我始终可以通过登录用户查找帐户并且非常一致?

一旦我拥有了帐户,祖先查询过程将确保内容检索的一致性,但我仍然坚持找出基于用户的祖先.

Nic*_*son 5

最简单和最好的方法是使用键名.在这种情况下,您的帐户实体的密钥名称应该是用户的ID.您可以创建如下帐户:

new_account = Account(owner=current_user, id=current_user.user_id(), name='Some Name')
Run Code Online (Sandbox Code Playgroud)

你可以这样查看它们:

existing_account = Account.get_by_id(current_user.user_id())
Run Code Online (Sandbox Code Playgroud)