Nested entities in Google App Engine. Do I do it right?

Posted by Aleksandr Makov on Programmers See other posts from Programmers or by Aleksandr Makov
Published on 2013-06-27T09:23:55Z Indexed on 2013/06/27 10:29 UTC
Read the original article Hit count: 263

Filed under:
|

Trying to make most of the GAE Datastore entities concept, but some doubts drill my head.

Say I have the model:

class User(ndb.Model):
    email = ndb.StringProperty(indexed=True)
    password = ndb.StringProperty(indexed=False)
    first_name = ndb.StringProperty(indexed=False)
    last_name = ndb.StringProperty(indexed=False)
    created_at = ndb.DateTimeProperty(auto_now_add=True)

    @classmethod
    def key(cls, email):
        return ndb.Key(User, email)

    @classmethod
    def Add(cls, email, password, first_name, last_name):
        user = User(parent=cls.key(email),
                    email=email,
                    password=password,
                    first_name=first_name,
                    last_name=last_name)
        user.put()
        UserLogin.Record(email)


class UserLogin(ndb.Model):
    time = ndb.DateTimeProperty(auto_now_add=True)

    @classmethod
    def Record(cls, user_email):
        login = UserLogin(parent=User.key(user_email))
        login.put()

And I need to keep track of times of successful login operations. Each time user logs in, an UserLogin.Record() method will be executed. Now the question — do I make it right?

Thanks.


EDIT 2

Ok, used the typed arguments, but then it raised this: Expected Key instance, got User(key=Key('User', 5418393301680128), created_at=datetime.datetime(2013, 6, 27, 10, 12, 25, 479928), email=u'[email protected]', first_name=u'First', last_name=u'Last', password=u'password'). It's clear to understand, but I don't get why the docs are misleading? They implicitly propose to use:

# Set Employee as Address entity's parent directly...
address = Address(parent=employee)

But Model expects key. And what's worse the parent=user.key() swears that key() isn't callable. And I found out the user.key works.


EDIT 1

After reading the example form the docs and trying to replicate it — I got type error: TypeError('Model constructor takes no positional arguments.'). This is the exacto code used:

user = User('[email protected]', 'password', 'First', 'Last')
user.put()

stamp = UserLogin(parent=user)
stamp.put()

I understand that Model was given the wrong argument, BUT why it's in the docs?

© Programmers or respective owner

Related posts about python

Related posts about google-app-engine