Ollie Cook
Ollie Cook

Reputation: 81

pattern for updating a datastore object

I'm wondering what the right pattern should be to update an existing datastore object using endpoints-proto-datastore.

For example, given a model like the one from your GDL videos:

class Task(EndpointsModel):
    detail = ndb.StringProperty(required=True)
    owner = ndb.StringProperty()

imagine we'd like to update the 'detail' of a Task.

I considered something like:

@Task.method(name='task.update',
             path='task/{id}',
             request_fields=('id', 'detail'))
def updateTask(self, task):
    pass

However, 'task' would presumably contain the previously-stored version of the object, and I'm not clear on how to access the 'new' detail variable with which to update the object and re-store it.

Put another way, I'd like to write something like this:

def updateTask(self, task_in_datastore, task_from_request):
    task_in_datastore.detail = task_from_request.detail
    task_in_datastore.put()

Is there a pattern for in-place updates of objects with endpoints-proto-datastore?

Thanks!

Upvotes: 0

Views: 232

Answers (2)

bossylobster
bossylobster

Reputation: 10163

See the documentation for details on this

The property id is one of five helper properties provided by default to help you perform common operations like this (retrieving by ID). In addition there is an entityKey property which provides a base64 encoded version of a datastore key and can be used in a similar fashion as id...

This means that if you use the default id property your current object will be retrieved and then any updates from the request will replace those on the current object. Hence doing the most trivial:

@Task.method(name='task.update',
             path='task/{id}',
             request_fields=('id', 'detail'))
def updateTask(self, task):
    task.put()
    return task

will perform exactly what you intended.

Upvotes: 1

Stubbies
Stubbies

Reputation: 3124

Task is your model, you can easily update like this:

@Task.method(name='task.update',
         path='task/{id}',
         request_fields=('id', 'detail'))
def updateTask(self, task):
    # Task.get_by_id(task.id)
    Task.detail = task.detail
    Task.put()
    return task

Upvotes: 0

Related Questions