views:

214

answers:

2

Using Google App Engine SDK and Python, I'm facing an issue : I'm unable to access the ID property of a given entity properties. The only properties I can access are those defined in my class Model, plus the key property (see answer below) :

class Question(db.Model):
    text = db.StringProperty()
    answers = db.StringListProperty()
    user = db.UserProperty()
    datetime = db.DateTimeProperty()

I can access text, answers, user, datetime and key properties just fine. However, I can't access the ID property. For example, after fetching all entities (using Question.all()) :

# OK Within a template, this will return a string :
{{ question.text }}
# OK, this will return the entity key :
{{ question.key }}

# KO this will return nothing :
{{ question.id }}

Any ideas ? Thanks !

+4  A: 

According to the documentation, there is no id() instance method defined for Model subclasses.

Try {{ question.key }} instead.

Also note that the key is not created until the entity is saved to the datastore.


Edit: more info based on OP's edit:

Since we're really after the numeric ID, we could do something like this in our template:

{{ question.key.id }}

Another note: you should never expect numeric IDs to increase in value corresponding with the order of entity creation. In practice, this is usually—but not always—the case.

Adam Bernier
Indeed, {{ question.key }} works fine and returns the key stored in the Datastore. I should have double-checked ! I might edit my original post. So I guess retrieving the ID is the only issue left.
Sorw
@Adam: thanks for the quick answers, solved my issues perfectly!
Sorw
@Sorw: Anytime. Welcome to SO.
Adam Bernier
+1  A: 

I just found a possible (inelegant, IMO) solution. After querying and fetching entities, loop through all of them and manually add the id parameter :

query = Question.all()
questions = query.fetch(10)

# Add ID property :
for question in questions:
    question.id = str(question.key().id())

I don't think it's efficient CPU wise, but it works as a quick/dirty fix.

Sorw
@Sorw: you don't have to do this. See my edited answer.
Adam Bernier
@Adam: hehe I think we both found a possible solution at the same time, but yours is a lot simplier !
Sorw
Inelegant, perhaps, but +1 to you for arriving at a solution.
Adam Bernier