LA_
LA_

Reputation: 20429

How to track newly added record to NDB datastore?

I've used the following code before:

def add_movie(movie_id, title, picture, description):
    movie = Movies(
        id=movie_id,
        title=title,
        picture=picture,
        description=description
        )
    movie.put()

but it didn't allow me know if movie was added as new record or if existing movie was update. So, I've changed the code to the following:

def add_movie(movie_id, title, picture, description):
    newly_added = True
    movie = Movies.get_by_id(movie_id)
    if movie:
        newly_added = False
    movie.id = movie_id
    movie.title = title
    movie.picture = picture
    movie.description = description
    movie.put()
    return newly_added

But looks like it will get movie first and only after that will update it. So 2 requests to datastore instead of 1.

Is there any other way to do the same? Or, am I wrong and both approaches are the same from performance perspective?

Upvotes: 0

Views: 109

Answers (2)

Shay Erlichmen
Shay Erlichmen

Reputation: 31928

As @Peter said: the get operations is very cheap and I wouldn't worry about it, but you can still store the movie id in the memcache and do a primarily check if its there, if its there then the movie is not new, if its not there check the datastore.

Upvotes: 2

Peter Knego
Peter Knego

Reputation: 80340

No, there is no other way around it.

This will impact the performance due to additional get request, but 'get' is quite fast and cheap, so do not worry about it.

Upvotes: 3

Related Questions