Google App Engine - Datastore get_or_insert key_na

2019-02-14 05:56发布

I am confused by get_or_insert(..). What should I pass as the key_name? Consider the following example:

class Person(db.model)
    name = db.StringProperty(required=True)

Assume that no two people can have the same name. Say I want to get or insert a new Person with name Peter, what would my get_or_insert statement look like?

Cheers,

Pete

2条回答
劫难
2楼-- · 2019-02-14 06:25

You can think of key_name like a primary key. Look at the docs for get_or_insert(...), there is an example of what the back-end code looks like.

If name is a unique field, you might want to use that as the key name too. Although I would suggest stripping white-space and normalizing case.

查看更多
Evening l夕情丶
3楼-- · 2019-02-14 06:26

The possibly confusing thing here is that the key doesn't show up directly in your model declaration, so that name = db.StringProperty bit in your example isn't needed. get_or_insert takes the keyname as its first (required) argument, so you're looking for code like:

person = Person.get_or_insert('Peter')
# other interesting & useful code here...
# later, maybe we need to retrieve that key name from the object:
name = person.key().name()
assert(name == "Peter")
查看更多
登录 后发表回答