I want to insert new entities programatically as well as manually. For 开发者_高级运维this I was thinking about using key_name to uniquely identify an entity.
The problem is that I don't know how to get the model to generate a new unique key name when I create the entity.
On the other hand, I cannot create the ID (which is unique across data store) manually.
How can I do "create unique key name if provided value is None"?
Thanks for your help!
If you really need a string id (as opposed to an automatically assigned integer id), you could use a random string generator, or unique id generator like uuid.uuid4.
I don't really understand your question. If you want an automatically-generated key name, just leave out the key when you instantiate the object - one will be automatically assigned when you call put()
.
If most of the time you want your entities to have automatically assigned ids, then just go around creating your entities (without passing a key
or key_name
), the key will be auto-assigned and your entities will have .key().id()
available.
If sometimes you need to assign the numeric ids manually, then you can reserve a block of ids so that AppEngine will never auto-assign them, and then you can use an id
from this reserved range whenever you want to assign an id to a known entity. To assign an id to an entity you create a Key
for that entity:
# reserve ids 4000 to 5000 for use manually on the Customer entity
db.allocate_id_range(db.Key.from_path('Customer',1),4000,5000)
# manualy create a customer with id 4501
bob = Customer(key=db.Key.from_path('Customer',4501), name='bob')
bob.put()
精彩评论