Gerard
Gerard

Reputation: 638

How to set users.userid as a key in ndb

I'm trying to write appengine python code that uses the built-in authentication 'users' object and using userid as an ndb key

Here's my model:

 class UserAccounts(ndb.Model):
     UserID = ndb.KeyProperty(required=True)

In my handler: I get the current user

user = users.get_current_user()

Instantiate an entry

account = Models.UserAccounts()

Set the userid to the ndb entry

account.UserID = userid

When I run it, I get this:

Expected Key, got '113804764227149124198'

Where am I going wrong? As much as possible, I'd like to use a KeyProperty instead of StringProperty for performance reasons.

Upvotes: 0

Views: 177

Answers (2)

marcadian
marcadian

Reputation: 2618

I think what you want is something like this UserAccounts(id=user_id), this way the user_id is the key. With this approach you can remove the userid field from the model definition

Upvotes: 0

mgilson
mgilson

Reputation: 309929

by:

account.UserID = userid

I assume you meant:

account.UserID = user.user_id()

The user id is a string, not a key, so you can't use a KeyProperty here. In fact, AFAIK, User objects as returned from users.get_current_user() don't have a key (at least not one that is documented) since they aren't datastore entries. There is an ndb.UserProperty, but I don't think it's use is generally encouraged.

What performance reasons are you referring to?

Upvotes: 1

Related Questions