get_by_id method on Model classes in Google App Engine Datastore

10,602

Solution 1

I just tried it 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>

Solution 2

An app's key is a list of (kind, id_or_name) tuples - for root entities, always only one element long. Thus, an ID alone doesn't identify an entity - the type of entity is also required. When you call db.Model.get_by_id(x), you're asking for the entity with key (Model, x). What you want is to call Address.get_by_id(x), which fetches the entity with key (Address, x).

Share:
10,602

Related videos on Youtube

tarn
Author by

tarn

Updated on April 15, 2022

Comments

  • tarn
    tarn about 2 years

    I'm unable to workout how you can get objects from the Google App Engine Datastore using get_by_id. Here is the 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 retrieve them with 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()
    

    A saved address has values 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 can't find them by id

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

    The address is None, 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: It turns out I'm an idiot and was trying find an Address Model in a function called Address. Thanks for your answers, I've marked Brandon as the correct answer as he got in first and demonstrated it should all work.