Using ndb.KeyProperty how to reference the same model?

ujjalcal picture ujjalcal · Sep 11, 2012 · Viewed 10.5k times · Source

I have a simple scenario where there is a User class which has the name, email and followers property.

class User(ndb.Model):
    name = ndb.StringProperty(required = True)
    search_name = ndb.StringProperty(required = True)
    pw_hash = ndb.StringProperty(required = True)
    email = ndb.StringProperty()

    follows = ndb.KeyProperty(Follow, repeated=True)
    followers = ndb.KeyProperty(User, repeated=True)

While executing this I am getting the error.

File "C:\ujjal\my project\cravel\code2\Users.py", line 46, in User
  followers = ndb.KeyProperty(User, repeated=True)
NameError: name 'User' is not defined
INFO     2012-09-11 11:45:23,953 dev_appserver.py:2967] "GET / HTTP/1.1" 500 -

Any suggestion as to how model the "followers" attribute would be highly appreciated. Thanks in Advance

Answer

Rob Curtis picture Rob Curtis · Sep 11, 2012

Using a kind on a key property e.g. some_prop = ndb.KeyProperty(User) only enforces that the kind of the key must be of kind User. So you can still use a KeyProperty without a kind if need be.

However, if you want to enforce that all follower keys must be of kind User(inside the User model) then surround the kind with quotes:

followers = ndb.KeyProperty(kind='User', repeated=True)

It's explained a little better in the ndb cheat sheet