The get_by_id method in model classes in the Google App Engine datastore

I can’t train how you can get objects from the Google App Engine data store using get_by_id. Here is a model

from google.appengine.ext import db class Address(db.Model): description = db.StringProperty(multiline=True) latitude = db.FloatProperty() longitdue = db.FloatProperty() date = db.DateTimeProperty(auto_now_add=True) 

I can create them, put them and get using gql.

 address = Address() address.description = self.request.get('name') address.latitude = float(self.request.get('latitude')) address.longitude = float(self.request.get('longitude')) address.put() 

The saved address is important for

 >> address.key() aglndWVzdGJvb2tyDQsSB0FkZHJlc3MYDQw >> address.key().id() 14 

I can find them using the key

 from google.appengine.ext import db address = db.get('aglndWVzdGJvb2tyDQsSB0FkZHJlc3MYDQw') 

But they cannot find them by id

 >> from google.appengine.ext import db >> address = db.Model.get_by_id(14) 

The address is missing when I try

 >> Address.get_by_id(14) AttributeError: type object 'Address' has no attribute 'get_by_id' 

How can I find by id?

EDIT: Turns out I'm an idiot and trying to find the address model in the Address function. Thanks for your answers, I identified Brandon as the correct answer when he came in first and demonstrated that everything should work.

+6
google-app-engine google-cloud-datastore
source share
3 answers

I just tried this on shell.appspot.com and it seems to work fine:

 Google Apphosting/1.0 Python 2.5.2 (r252:60911, Feb 25 2009, 11:04:42) [GCC 4.1.0] >>> class Address(db.Model): description = db.StringProperty(multiline=True) latitude = db.FloatProperty() longitdue = db.FloatProperty() date = db.DateTimeProperty(auto_now_add=True) >>> addy = Address() >>> addyput = addy.put() >>> addyput.id() 136522L >>> Address.get_by_id(136522) <__main__.Address object at 0xa6b33ae3bf436250> 
+22
source share

The application key is a list (kind, id_or_name) of tuples - for root objects, always only one element is long. Thus, only an identifier does not identify an object - an object type is also required. When you call db.Model.get_by_id (x), you request an entity with the key (Model, x). You want to call Address.get_by_id (x), which retrieves the object with the key (Address, x).

+6
source share

You must use the long type in get_by_id ("here"). Type Int must have an error message.

0
source share

All Articles