繁体   English   中英

如何将ID / KEY分配给Google Appengine数据存储区中的实体,以及如何根据密钥进行检索

[英]How to assign ID/KEY to the entity in Google Appengine Datastore, and how to retrieve based on key

假设我有一个使用db的Post实体。

class Post(db.Model):
    subject = db.StringProperty(required = True)
    content = db.TextProperty(required = True)
    created = db.DateTimeProperty(auto_now_add = True)
    last_modified = db.DateTimeProperty(auto_now = True)

如果我的代码是这样的,我如何为每个博客帖子分配ID,以及如何使用密钥检索帖子。 非常感谢

您有2个选择:

1:指定您自己的密钥名称 (另请参见使用数字密钥ID ):

new_post = Post(id="post12345",              # MUST be unique!
                subject="The Subject",
                content="blah")
key = new_post.put()
id = key.id()  # will be the "post12345" value we specified

2:让Cloud Datastore生成用于密钥的ID

new_post = Post(subject="The Subject",
                content="blah")
key = new_post.put()
id = key.id()  # will be a numeric ID generated by google

不管用于创建实体的方法如何(使用指定的或自动生成的ID),您都可以通过ID或键来检索对象,以方便者为准(假设在下面的示例代码中都可用):

post1 = Post.get_by_id(id)
post2 = key.get()
assert post1.key == post2.key

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM