1
votes

Suppose I have create a new entity as follows:

item = Item()
item.property = property_value
item_key1 = item.put()

Question 1: In the same file immediately after this line, what happens if I do the following:

item_key2 = item.put()

Now, does datastore have one entity - item, or do datastore have two entities identified by item_key1 and item_key2, respectively?

Question 2: In the same file immediately after this line (without the code added in Question 1), what happens if I do the following:

item.property = new_property_value
item.put()

Does the same entity in datastore get updated, or does datastore create a new entity with property equals to new_property_value?

A follow up question to Question 2: If datastore creates two entities in this case, does it mean I have to do the following to update an entity, even if the entity was just created in the same function?

item = Item() 
item.property = property_value
# entity written to datastore
item_key = item.put() 
# get the entity from the datastore to make sure it is the entity to update
item = item_key.get() 
# update the value
item.property = new_property_value
# put it back to datastore
item.put() 

This looks very silly, and cost twice as much in datastore write.

Thanks.

1

1 Answers

4
votes

The answer to both of your questions is that you will only have one entity.

When you put an entity to the datastore, it always overwrites the existing entity with the same key. Once you call put(), your item has a unique key. Now every subsequent put() on the same item will overwrite the existing entity in the datastore.

You will have two entities only in the following case:

item = Item()
item_key1 = item.put()

item = Item()
item_key2 = item.put()