Failed to access the ID property from the data store object

Using the Google App Engine and Python SDKs, I ran into a problem: I cannot access the ID property for these object properties. The only properties available to me are those defined in my 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 texts, answers, users, dates, and key properties. However, I cannot access the ID property. For example, after retrieving all the objects (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!

+6
python google-app-engine entity google-cloud-datastore
source share
2 answers

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

Try {{ question.key }} .

Also note that the key is not created until the object is stored in the data warehouse.


Edit: more info based on OP editing:

Since we are really after the numeric identifier , we could do something like this in our template:

{{ question.key.id }}

Another note: you should never expect numeric identifiers to increase in value in the order in which the entity was created. In practice, this is usually - but not always - the case.

+10
source share

I just found a possible (inelegant, IMO) solution. After querying and fetching entities, swipe all of them in turn 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 this is an efficient processor, but it works as a quick / dirty fix.

+5
source share

All Articles