Python NDB使用用户API形成实体组
我试图把我的头脑集中在一个看似非常简单的用例上,但我似乎失败得很惨。本练习的目标是在高复制数据存储中查找使用Google帐户用户名登录的用户的一组记录,并保持极其一致 我的数据如下所示:Python NDB使用用户API形成实体组,python,google-app-engine,google-cloud-datastore,data-modeling,Python,Google App Engine,Google Cloud Datastore,Data Modeling,我试图把我的头脑集中在一个看似非常简单的用例上,但我似乎失败得很惨。本练习的目标是在高复制数据存储中查找使用Google帐户用户名登录的用户的一组记录,并保持极其一致 我的数据如下所示: class Account(ndb.Model): owner = ndb.UserProperty() name = ndb.StringProperty() class Content(ndb.Model): content = ndb.StringProperty() new_
class Account(ndb.Model):
owner = ndb.UserProperty()
name = ndb.StringProperty()
class Content(ndb.Model):
content = ndb.StringProperty()
new_account = Account(owner=current_user, id=current_user.user_id(), name='Some Name')
existing_account = Account.get_by_id(current_user.user_id())
当我第一次创建帐户时,我只需执行以下操作:
current_user = users.get_current_user()
new_account = Account(owner=current_user, name='Some Name')
new_account.put()
现在创建内容:
new_content = Content(parent=new_account.key, content='Some Content')
new_content.put()
当用户登录时,我只能按UserProperty进行查询,但我似乎无法将用户设置为实体组的父级,因此如何确保我始终可以按登录用户查找帐户,并且非常一致
一旦我拥有了帐户,祖先查询过程将确保内容检索的一致性,但我一直坚持根据用户确定祖先。我不确定您为什么要这样做,但您也必须为
帐户创建父实体,因此,您可以使用祖先对其执行查询。最简单、最好的方法是使用键名。在这种情况下,帐户实体的密钥名称应该是用户的ID。您可以创建如下帐户:
class Account(ndb.Model):
owner = ndb.UserProperty()
name = ndb.StringProperty()
class Content(ndb.Model):
content = ndb.StringProperty()
new_account = Account(owner=current_user, id=current_user.user_id(), name='Some Name')
existing_account = Account.get_by_id(current_user.user_id())
您可以这样查找它们:
class Account(ndb.Model):
owner = ndb.UserProperty()
name = ndb.StringProperty()
class Content(ndb.Model):
content = ndb.StringProperty()
new_account = Account(owner=current_user, id=current_user.user_id(), name='Some Name')
existing_account = Account.get_by_id(current_user.user_id())
哦,天哪。我以为他想为每个用户创建多个帐户实体。如果您只是想确保查询帐户实体时的一致性,那么@NickJohnson的答案就是正确的选择。:)谢谢你,尼克!这正是我想要的。我想我在文档中遗漏了它。为了扩展一下Nick的建议,我实际上正在使用一个映射实体,它将用户ID映射到一个帐户密钥。这样,一个帐户可以有多个用户,但仍然使用get()检索该帐户。文档还建议不要存储UserProperty,因为如果用户更改其电子邮件地址,则可能会导致不一致: