ajskhan
ajskhan

Reputation: 115

Updating an entry in GAE Datastore

Quick question (probably a basic one!).

I am using Google App Engine with Flask. I have the following DB:

class Bear(db.Model):
bear_id = db.IntegerProperty()
pair = db.IntegerProperty()
status = db.IntegerProperty()
time = db.IntegerProperty() 

I add to this via URL parameters here:

@app.route('/add')
def add():
    rightNow = int(time.time())
    cur_id = int( request.args.get('id') )
    cur_status = int( request.args.get('status') )

    newEntry = Bear(
        time = rightNow,
        bear_id = cur_id,
        status = cur_status,
        # key_name = str(cur_id)
    )

    newEntry.put()  

    return 'added'

And (try to) update it here, again via URL parameters:

@app.route('/update')
def update():
    rightNow = int(time.time())
    cur_id = int( request.args.get('id') )
    cur_status = int( request.args.get('status') )

    address_k = db.Key.from_path('bear_id', cur_id)

    address = db.get(address_k)

    address.status = cur_status;
    address.put()   

    return 'cur_id'

I am trying to pull the datastore entity by using the bear_id string, but I am noticing that I am getting the wrong key stored in address_k. It does not match the key that I can see in my datastore. I am not sure why this is happening. Any thoughts?

Upvotes: 1

Views: 37

Answers (2)

marcadian
marcadian

Reputation: 2618

This is happened because you insert using id as int, and you retrieve using id as str. Datastore treat them differently, so you should be consistent.

Upvotes: 1

ajskhan
ajskhan

Reputation: 115

I ended up doing the following:

In add, I added the key_name to be a string of the ID

@app.route('/add')
def add():
    rightNow = int(time.time())
    cur_id = int( request.args.get('id') )
    cur_status = int( request.args.get('status') )

    newEntry = Bear(
        time = rightNow,
        bear_id = cur_id,
        status = cur_status,
        key_name = str(cur_id)
    )

    newEntry.put()  

    return 'added'

and then when updating, I was able to pull it like this:

@app.route('/update')
def update():
    rightNow = int(time.time())
    cur_id = int( request.args.get('id') )
    cur_status = int( request.args.get('status') )

    address_k = db.Key.from_path('Bear', str(cur_id))    
    address = db.get(address_k)

    address.status = cur_status;
    address.put()   

    return cur_id

And it works!

Upvotes: 0

Related Questions