NDB using Users API to form an entity group

2019-07-22 00:09发布

I'm trying to wrap my head around what seems to be a very simple use case, but I seem to be failing miserably. The goal of the exercise is to look up a set of records for the user that logs in using the Google Accounts username within the high replication datastore and be extremely consistent.

My data looks like this:

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

class Content(ndb.Model):
    content = ndb.StringProperty()

When I first create the account, I just do the following:

current_user = users.get_current_user()
new_account = Account(owner=current_user, name='Some Name')
new_account.put()

Now create content:

new_content = Content(parent=new_account.key, content='Some Content')
new_content.put()

When the user logs in, I can only query by UserProperty, but I seem to be unable to set user as the parent for an entity group, so how do I make sure that I always can look-up the Account by the logged in user and be extremely consistent?

Once I have the account, the ancestor query process will ensure consistency for content retrieval, but I'm stuck on figuring out ancestry based on User.

2条回答
霸刀☆藐视天下
2楼-- · 2019-07-22 00:43

I'm not sure why exactly you want to do that, but you have to create a parent entity for Account as well, so that you can perform queries on it with an ancestor.

查看更多
欢心
3楼-- · 2019-07-22 00:46

The easiest and best way to do this is using key names. In this case, the key name for your Account entity should be the ID of the user. You can create accounts like this:

new_account = Account(owner=current_user, id=current_user.user_id(), name='Some Name')

And you can look them up like this:

existing_account = Account.get_by_id(current_user.user_id())
查看更多
登录 后发表回答