Snowman
Snowman

Reputation: 32061

Generating a key from ancestor path in Google App Engine

I have a model called Request. A request is created with a parent User like so:

request = Request(parentUserKey)

Now, the key_name for a User is that user's email, so when I create a new user, I do:

user = User(key_name = '[email protected]')

So what I want to do now is to create a key using Key.from_path for a Request, so I try:

requestKey = Key.from_path('User', '[email protected]', 'Request', 1)

I put 1 because I will use this key to fetch all Requests with ID higher than 1 (or any other arbitrary int) via the following:

requestQuery.filter("__key__ >", requestKey)

Then for testing purposes, I try to convert the key to a string via keyString = str(requestKey), but I get the following error:

Cannot string encode an incomplete key

What am I doing wrong?

Upvotes: 0

Views: 722

Answers (2)

Adam Crossland
Adam Crossland

Reputation: 14213

To elaborate on what Guido wrote, doing all of this work to manually create a key probably isn't the best approach to solve your problem. Rather, if you store all of User's Request entities in User's entity group, you can simply and straight-forwardly retrieve them with an ancestor query.

First, to make all of the Request entities children of User, we're going to slightly change the way that you instantiate a Request object:

request = Request(parent=parentUser) # Where parentuser is a User already in the datastore
# Do whatever else you need to do to initialize this entity
request.put()

Now, to get all of the Request objects that belong to User, you just:

requests = Request.all().ancestor(parentUser).fetch(1000)
# Obviously, you want to intelligently manage the condition of having
# more that 1000 Requests using cursors if need be.

Having the ability to manually create Keys using all of the path info is great, but it is also often more work than is necessary.

Does this solve your use-case?

Upvotes: 2

Guido van Rossum
Guido van Rossum

Reputation: 16890

A key with a 0 id is not valid. Instead of that filter, use an ancestor query.

Upvotes: 1

Related Questions