0

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.

K DawG
  • 13,287
  • 9
  • 35
  • 66
Gerard
  • 638
  • 4
  • 8
  • 19

2 Answers2

1

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?

mgilson
  • 300,191
  • 65
  • 633
  • 696
  • Your assumption of account.UserID = user.user_id() is correct. What I'm trying to solve is that in here [link]https://developers.google.com/appengine/docs/python/ndb/queries there is talk about "If you are sure that there was just one Account with that userid, you might prefer to use userid as a key. Account.get_by_id(...) is faster than Account.query(...).get()." By saying use userid as a key, I assumed it mean to set it as a KeyProperty. Is that correct? – Gerard Dec 22 '13 at 00:30
  • @Gerard -- No, don't make it a KeyProperty. It means that you set it as the ID when you create an instance: `account = UserAccount(id=user_id)` and then `account = UserAccount.get_by_id(user_id)` – mgilson Dec 24 '13 at 01:08
0

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

marcadian
  • 2,608
  • 13
  • 20
  • I've been doing research, the answer I found is similar to: this:http://stackoverflow.com/questions/13058327/google-app-engine-ndb-custom-key-id I was confusing Keys to IDs. In the RDBMS world, an ID is a tuple and thought I have to include it in the model. So the solution is, I will use StringProperty for the UserID field. But upon creation of an object, I will include the ID='' parameter. – Gerard Dec 22 '13 at 22:53